Advertisement
Advertisement


jQuery get specific option tag text


Question

All right, 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.

2020/08/20
1
1240
8/20/2020 2:25:33 PM

Accepted Answer

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()
2020/04/19
1124
4/19/2020 11:14:35 AM


This worked perfectly for me, I was looking for a way to send two different values with options generated by MySQL, and the following is generic and dynamic:

$(this).find("option:selected").text();

As mentioned in one of the comments. With this I was able to create a dynamic function that works with all my selection boxes that I want to get both values, the option value and the text.

Few days ago I noticed that when updating the jQuery from 1.6 to 1.9 of the site I used this code, this stop working... probably was a conflict with another piece of code... anyway, the solution was to remove option from the find() call:

$(this).find(":selected").text();

That was my solution... use it only if you have any problem after updating your jQuery.

2016/11/29

Based on the original HTML posted by Paolo I came up with the following.

$("#list").change(function() {
    alert($(this).find("option:selected").text()+' clicked!');
});

It has been tested to work on Internet Explorer and Firefox.

2011/05/25

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

for multiple selected value in the #list element.

2011/09/23

  1. If there is only one select tag in on the page then you can specify select inside of id 'list'

    jQuery("select option[value=2]").text();
    
  2. To get selected text

    jQuery("select option:selected").text();
    
2016/08/19

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.

2008/10/13

Source: https://stackoverflow.com/questions/196684
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]