[javascript] jQuery get specific option tag text

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.

This question is related to javascript jquery jquery-selectors html-select

The answer is


I needed this answer as I was dealing with a dynamically cast object, and the other methods here did not seem to work:

element.options[element.selectedIndex].text

This of course uses the DOM object instead of parsing its HTML with nodeValue, childNodes, etc.


Try

[...list.options].find(o=> o.value=='2').text

_x000D_
_x000D_
let text = [...list.options].find(o=> o.value=='2').text;

console.log(text);
_x000D_
<select id='list'>
    <option value='1'>Option A</option>
    <option value='2'>Option B</option>
    <option value='3'>Option C</option>
</select>
_x000D_
_x000D_
_x000D_


This is an old Question which has not been updated in some time the correct way to do this now would be to use

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

I hope this helps :-)


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

I wanted a dynamic version for select multiple that would display what is selected to the right (wish I'd read on and seen $(this).find... earlier):

<script type="text/javascript">
    $(document).ready(function(){
        $("select[showChoices]").each(function(){
            $(this).after("<span id='spn"+$(this).attr('id')+"' style='border:1px solid black;width:100px;float:left;white-space:nowrap;'>&nbsp;</span>");
            doShowSelected($(this).attr('id'));//shows initial selections
        }).change(function(){
            doShowSelected($(this).attr('id'));//as user makes new selections
        });
    });
    function doShowSelected(inId){
        var aryVals=$("#"+inId).val();
        var selText="";
        for(var i=0; i<aryVals.length; i++){
            var o="#"+inId+" option[value='"+aryVals[i]+"']";
            selText+=$(o).text()+"<br>";
        }
        $("#spn"+inId).html(selText);
    }
</script>
<select style="float:left;" multiple="true" id="mySelect" name="mySelect" showChoices="true">
    <option selected="selected" value=1>opt 1</option>
    <option selected="selected" value=2>opt 2</option>
    <option value=3>opt 3</option>
    <option value=4>opt 4</option>
</select>

As an alternative solution, you can also use a context part of jQuery selector to find <option> element(s) with value="2" inside the dropdown list:

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

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.


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.


Use:

function selected_state(){
    jQuery("#list option").each(function(){
        if(jQuery(this).val() == "2"){
            jQuery(this).attr("selected","selected");
            return false;
        }
    });
}

jQuery(document).ready(function(){
    selected_state();
});

I was looking for getting val by internal field name instead of ID and came from google to this post which help but did not find the solution I need, but I got the solution and here it is:

So this might help somebody looking for selected value with field internal name instead of using long id for SharePoint lists:

var e = $('select[title="IntenalFieldName"] option:selected').text(); 

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

Try this:

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

Try

[...list.options].find(o=> o.value=='2').text

_x000D_
_x000D_
let text = [...list.options].find(o=> o.value=='2').text;

console.log(text);
_x000D_
<select id='list'>
    <option value='1'>Option A</option>
    <option value='2'>Option B</option>
    <option value='3'>Option C</option>
</select>
_x000D_
_x000D_
_x000D_


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

leave a space after the id selector.


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

I needed this answer as I was dealing with a dynamically cast object, and the other methods here did not seem to work:

element.options[element.selectedIndex].text

This of course uses the DOM object instead of parsing its HTML with nodeValue, childNodes, etc.


I wanted a dynamic version for select multiple that would display what is selected to the right (wish I'd read on and seen $(this).find... earlier):

<script type="text/javascript">
    $(document).ready(function(){
        $("select[showChoices]").each(function(){
            $(this).after("<span id='spn"+$(this).attr('id')+"' style='border:1px solid black;width:100px;float:left;white-space:nowrap;'>&nbsp;</span>");
            doShowSelected($(this).attr('id'));//shows initial selections
        }).change(function(){
            doShowSelected($(this).attr('id'));//as user makes new selections
        });
    });
    function doShowSelected(inId){
        var aryVals=$("#"+inId).val();
        var selText="";
        for(var i=0; i<aryVals.length; i++){
            var o="#"+inId+" option[value='"+aryVals[i]+"']";
            selText+=$(o).text()+"<br>";
        }
        $("#spn"+inId).html(selText);
    }
</script>
<select style="float:left;" multiple="true" id="mySelect" name="mySelect" showChoices="true">
    <option selected="selected" value=1>opt 1</option>
    <option selected="selected" value=2>opt 2</option>
    <option value=3>opt 3</option>
    <option value=4>opt 4</option>
</select>

Try this:

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

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

leave a space after the id selector.


Use:

function selected_state(){
    jQuery("#list option").each(function(){
        if(jQuery(this).val() == "2"){
            jQuery(this).attr("selected","selected");
            return false;
        }
    });
}

jQuery(document).ready(function(){
    selected_state();
});

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

for multiple selected value in the #list element.


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.


You can get selected option text by using function .text();

you can call the function like this :

jQuery("select option:selected").text();

A tip: you can use below code if your value is dynamic:

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

Or (better style)

$("#list option").filter(function() {
     return this.value === aDynamicValue;
}).text();

As mentioned in jQuery get specific option tag text and placing dynamic variable to the value


You can get selected option text by using function .text();

you can call the function like this :

jQuery("select option:selected").text();

You can get one of following ways

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

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

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

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

_x000D_
_x000D_
$(function(){    _x000D_
    _x000D_
    console.log($("#list").find('option').filter('[value=2]').text());_x000D_
    console.log($("#list").find('option[value=2]').text());_x000D_
    console.log($("#list").children('option[value=2]').text());_x000D_
    console.log($("#list option[value='2']").text());_x000D_
    _x000D_
});
_x000D_
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>_x000D_
<select id='list'>_x000D_
    <option value='1'>Option A</option>_x000D_
    <option value='2'>Option B</option>_x000D_
    <option value='3'>Option C</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_


I wanted to get the selected label. This worked for me in jQuery 1.5.1.

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

$(this).children(":selected").text()

This is an old Question which has not been updated in some time the correct way to do this now would be to use

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

I hope this helps :-)


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.


A tip: you can use below code if your value is dynamic:

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

Or (better style)

$("#list option").filter(function() {
     return this.value === aDynamicValue;
}).text();

As mentioned in jQuery get specific option tag text and placing dynamic variable to the value


While "looping" through dynamically created select elements with a .each(function()...): $("option:selected").text(); and $(this + " option:selected").text() did not return the selected option text - instead it was null.

But Peter Mortensen's solution worked:

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

I do not know why the usual way does not succeed in a .each() (probably my own mistake), but thank you, Peter. I know that wasn't the original question, but am mentioning it "for newbies coming through Google."

I would have started with $('#list option:selected").each() except I needed to grab stuff from the select element as well.


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.


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

for multiple selected value in the #list element.


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.


You can get one of following ways

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

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

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

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

_x000D_
_x000D_
$(function(){    _x000D_
    _x000D_
    console.log($("#list").find('option').filter('[value=2]').text());_x000D_
    console.log($("#list").find('option[value=2]').text());_x000D_
    console.log($("#list").children('option[value=2]').text());_x000D_
    console.log($("#list option[value='2']").text());_x000D_
    _x000D_
});
_x000D_
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>_x000D_
<select id='list'>_x000D_
    <option value='1'>Option A</option>_x000D_
    <option value='2'>Option B</option>_x000D_
    <option value='3'>Option C</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_


$(this).children(":selected").text()

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

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.


I was looking for getting val by internal field name instead of ID and came from google to this post which help but did not find the solution I need, but I got the solution and here it is:

So this might help somebody looking for selected value with field internal name instead of using long id for SharePoint lists:

var e = $('select[title="IntenalFieldName"] option:selected').text(); 

While "looping" through dynamically created select elements with a .each(function()...): $("option:selected").text(); and $(this + " option:selected").text() did not return the selected option text - instead it was null.

But Peter Mortensen's solution worked:

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

I do not know why the usual way does not succeed in a .each() (probably my own mistake), but thank you, Peter. I know that wasn't the original question, but am mentioning it "for newbies coming through Google."

I would have started with $('#list option:selected").each() except I needed to grab stuff from the select element as well.


As an alternative solution, you can also use a context part of jQuery selector to find <option> element(s) with value="2" inside the dropdown list:

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

I wanted to get the selected label. This worked for me in jQuery 1.5.1.

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

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.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to jquery-selectors

Why is my JQuery selector returning a n.fn.init[0], and what is it? How to use placeholder as default value in select2 framework Access the css ":after" selector with jQuery jQuery: using a variable as a selector Check if any ancestor has a class using jQuery jQuery selector first td of each row Select element by exact match of its content jQuery selector to get form by name jQuery : select all element with custom attribute Set select option 'selected', by value

Examples related to html-select

How can I get new selection in "select" in Angular 2? How to show disable HTML select option in by default? Remove Select arrow on IE Bootstrap 3 select input form inline Change <select>'s option and trigger events with JavaScript How to use a Bootstrap 3 glyphicon in an html select Creating a select box with a search option Drop Down Menu/Text Field in one How to have a default option in Angular.js select box How to set the 'selected option' of a select dropdown list with jquery