jQuery get specific option tag text

jQuery get specific option tag text

All right, say I have this:

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.

Solutions/Answers:

Solution 1:

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

Solution 2:

If you’d like to get the option with a value of 2, use

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

If you’d like to get whichever option is currently selected, use

$("#list option:selected").text();

Solution 3:

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.

Solution 4:

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.

Solution 5:

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

for multiple selected value in the #list element.

Solution 6:

  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();