views:

62924

answers:

8

Alright, say I have this:

<select id='list'>
<option value='1'>Option A</option>
<option value='2'>Option B</option>
<option value='3'>Option C</option>
</select>

What would the selector look like if I wanted to get "Option B" when I have the value '2'. Please note that this is not asking how to get the selected text value, but just any one of them, whether selected or not, depending on the value attribute. I tried:

$("#list[value='2']").text();

But it is not working.

+68  A: 

It's looking for an element with id list which has a property value equal to 2. What you want is the option child of the list.

$("#list option[value='2']").text()
nickf
+7  A: 

Try the following:

$("#list option[value=2]").text();

The reason why your original snippet wasn't working is because your OPTION tags are children to your SELECT tag, which has the id list.

Andrew Moore
+46  A: 
$("#list option:selected").text();
this is to get the current selected option text, more details about this issue: http://marcgrabanski.com/article/jquery-select-list-values
Amr ElGarhy
Not what was asked for though
WmasterJ
To get the value instead of the text, you will need to write:- $("select#list").val(); I know that this is not the actual answer of the question asked, but still thought of mentioning this point for newbies coming through Google.
Knowledge Craving
Thank you for this answer, though, it helped me with something else.
gknauth
+1  A: 
$("#list [value='2']").text();

leave a space after the id selector.

Mon
+1  A: 
$("#list option:selected").each(function() {
   alert($(this).text());
}

for multiple selected value in the #list element.

m3ct0n
A: 

Hi

Interesting. But how do I select an id instead of text. Basically what I'm trying to do is that when u select an option from the drop down above; it must pass an id of the selected option to a function that will fetch other data from a different table (we can even use an array its fine), then populates the second dropo down list ???

Tiza
This should be asked as a separate question, not posted as an answer. Please use the **[Ask Question]** button at the top right of the page.
Bill the Lizard
+2  A: 

Wouldn't that be:

$("#list option:selected").attr('id');
Robbert
+1  A: 

Guys,dont forget this:change(fn)

Jake