Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 414
Zuhaib Avatar asked Mar 01 '23 04:03

Zuhaib


2 Answers

Use

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

Also a good article on

jQuery - Select elements - tips and tricks

like image 192
rahul Avatar answered Mar 02 '23 16:03

rahul


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

$('#selValues').get(0).selectedIndex=2; 
like image 39
kgiannakakis Avatar answered Mar 02 '23 18:03

kgiannakakis