How to use jQuery to find the selected index on a DOM object?

Given the following javascript:

function foo(selectControl) { ... }

and the following html:

<select onchange="foo(this)"> ...

In jQuery, how can I simulate the following functions:

$('#selectList :selected').text();

when instead I go around a real DOM object. I know that I can wrap a DOM object and call operations like

$(selectControl).val();

but I specifically ask how to replicate the jQuery string selector mechanism:

$('#selectList :selected')
+3
source share
3 answers

You can use the jQuery function context argument:

$(':selected', selectControl).text();

See an example here .

Although I would recommend you programmatically bind events:

$('#selectID').change(function () {
  //...
});
+3
source

You ask how to do it initially without jQuery? I believe this will be:

selectControl.options[selectControl.selectedIndex]

.value .text.

+1

, select:

var select = document.getElementById('selectId');

You can get the text of the selected option as follows:

var text = select.options[select.selectedIndex].innerHTML;

(Yes, that gets the HTML, but you can dig and get the text node if you want.)

0
source

Source: https://habr.com/ru/post/1734735/


All Articles