views:

277

answers:

4

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?

+1  A: 

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

$('#selValues').get(0).selectedIndex=2;
kgiannakakis
+2  A: 

Use

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

Also a good article on

jQuery - Select elements - tips and tricks

rahul
Yes that statement would work, I know that. But if the value you are trying to select is not present in the list, then the selected value should change to -1 (no items selected). But it doesn't happen with this statement.
Zuhaib
+2  A: 

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>
Michał Kwiatkowski
You are right .. but it doesn't solve my issue .. If I specify the value in the selector it will work.'#selValues option[value="3"]'But if the value that I am trying to select is not present in the list, then no item should be selected. This doesn't happen with jQuery but happens with normal JavaScript if I just write:$('#selValues')[0].value = <Value Here>;
Zuhaib
+1  A: 

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

Guy C