admin管理员组

文章数量:1390391

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?

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?

Share Improve this question asked Oct 21, 2009 at 7:30 ZuhaibZuhaib 1,4203 gold badges18 silver badges36 bronze badges 2
  • 1 Post this as a bug over at jquery. – Marius Commented Oct 21, 2009 at 7:34
  • 3 It's not a bug, it's a feature, as I explained in my answer. – Michał Kwiatkowski Commented Oct 21, 2009 at 7:48
Add a ment  | 

4 Answers 4

Reset to default 2

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./day-01#backwards

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

本文标签: javascriptjQuery val() on HTML Select Text takes precedence over ValueStack Overflow