How do I use JQuery to find the selected index on a DOM select object?
Given the following javascript:
function foo(selectControl) { ... }
and the following html:
<select onchange="foo(this)"> ...
In JQuery, how do I simulate the following functionality:
$('#selectList :selected').text();
when instead, I am passing around the real DOM object. I know I can wrap the DOM开发者_StackOverflow社区 object up and invoke operations like
$(selectControl).val();
but I'm specifically asking how to replicate JQuery's string selector mechanism:
$('#selectList :selected')
You can use the context argument of the jQuery function:
$(':selected', selectControl).text();
Check an example here.
Although I would recommend you to bind the events programmatically:
$('#selectID').change(function () {
//...
});
You're asking how to do this natively, without jQuery? I believe it would be:
selectControl.options[selectControl.selectedIndex]
and then .value
or .text
off of that.
Let's say you grab the select element:
var select = document.getElementById('selectId');
You can get the text of the selected option like this:
var text = select.options[select.selectedIndex].innerHTML;
(Yes that gets the HTML, but you could dig down and get the text node contents if you wanted.)
精彩评论