开发者

How do I use JQuery to find the selected index on a DOM select object?

开发者 https://www.devze.com 2022-12-21 06:32 出处:网络
Given the following javascript: function foo(selectControl) { ... } and the following html: <select onchange=\"foo(this)\"> ...

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.)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号