tags:

views:

100

answers:

3

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 object up and invoke operations like

$(selectControl).val();

but I'm specifically asking how to replicate JQuery's string selector mechanism:

$('#selectList :selected')
+3  A: 

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 () {
  //...
});
CMS
+1  A: 

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.

beamrider9
Is there really a "text" attribute on `<option>` tags? I guess there might be.
Pointy
A: 

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

Pointy