开发者

jQuery val() on HTML Select Text takes precedence over Value

Take the below HTML select for an example:

<select name="selValues" id="selValues">
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">5</option>
    <option value="4">3</option>
</select>

If we write the开发者_运维百科 following jQuery statement:

$('#selValues').val('2'); // Two will get selected
$('#selValues').val('3'); // 3 will get selected instead of 5??

Why is it like that?


Use

$("#selValues option[value='3']").attr('selected', 'selected');

Also a good article on

jQuery - Select elements - tips and tricks


The val() method gets or sets the selected text. You may want to use selectedIndex instead:

$('#selValues').get(0).selectedIndex=2; 


When selecting options jQuery looks first at the value then at the text of an option. It also goes through options in order. So, $('#selValues').val('3') selects options 3 first, but right after that changes selection to option 4 (as it has the text "3"). Use a multiple select to see that in fact both options are selected

<select name="selValues" id="selValues" multiple="multiple">
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">5</option>
    <option value="4">3</option>
</select>


As of JQuery 1.4 this has now been made unambiguous. It will now select by value, not by text value http://jquery14.com/day-01#backwards

If you do need to still select by value then a suggested method is here

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜