JQuery retrieving text instead of value of select list

I need to get the value from a select list but JQuery is returning the text within the options of the select.

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>

I then use the following JQuery, which I thought would get me the value

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

but when I look at myOption I get the text of 'One' or 'two'?


update : add val().

console.log($('#myselect').val());

// all option's 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/


to get the text value easiest way is

For selected option Text :

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

For selected option value:

$("select#myselect").val(); 

I had this problem because the jQuery Val() function was in my head and I actually defined the options as <option val='xx'> instead of <option value='xx'> . That's what is causing the problem. See this updated jsfiddle.

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

<select id="myselect2">
   <option val="1">One</option>
   <option val="2">Two</option>
</select>

<script>
$('select').change(function() {
    alert($(this).val());
});
</script>

The first select will alert "1" or "2" and the second select will alert "One" or "Two".

链接地址: http://www.djcxy.com/p/83074.html

上一篇: jQuery获取选择列表的文本值

下一篇: JQuery检索文本而不是选择列表的值