JQuery retrieves text instead of the value of the selected list

I need to get a value from a select list, but jQuery returns the text in the select options.

I have the following simple code.

<select id="myselect"> <option selected="selected">All</option> <option value="1">One</option> <option value="2">Two</option> </select> 

Then I use the following jQuery, which I thought would get the value

 var myOption = $('#myselect').val() 

but when I look at myOption , do I get the text "One" or "Two"?

+7
source share
4 answers

update: add val ().

 console.log($('#myselect').val()); // all option value $('#myselect').find('option').each(function(){ console.log($(this).text()); console.log($(this).val()); }); // change event $('#myselect').change(function(){ console.log($(this).find(':selected').text()); console.log($(this).find(':selected').val()); }); 

demo: http://jsfiddle.net/yLj4k/3/

+9
source

the easiest way to get a text value is

For the selected Text option:

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

For the selected option value:

 $("select#myselect").val(); 
+2
source

change

Chia

working demo here: using text http://jsfiddle.net/QtjTq/3/ && & &&& & using val here http://jsfiddle.net/QtjTq/4/

like this for accessing the text () - var myOption = $('#myselect option:selected').text() for accessing the value - var myOption = $('#myselect option:selected').val()

more details:

for value , if you want to access the attribute value= use .val() ;

for text , if you want to get text ie one or two , then use the selected options ... option:selected with .text() api.

further if you want to read http://forum.jquery.com/topic/jquery-using-val-vs-text

hope this helps :) cheers

 var myOption = $('#myselect option:selected').text() //**or whatever suit you** var myOption = $('#myselect option:selected').val() <select id="myselect"> <option value="1">One</option> <option value="2">Two</option> </select> 
0
source

Demo

 $("#myselect").change(function() { alert(this.options[this.selectedIndex].value); }); 
0
source

All Articles