The jQuery select box.val ('') field is different from 1.9 to 1.10+, which is the shortest way to do this

The following behaves differently between jQuery 1.9 and 1.10 +:

<select id="s1"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> $('#s1 option[value=1]').hide(); $('#s1').val(''); 

The idea of ​​this code is to choose the first option.

After 1.10, the $('#s1').val(''); stops working the same way. I suppose it was never intended to be used that way, but its old code and somehow had to be upgraded ...

After jQuery 1.10, nothing is selected, and $('#s1').val() returns null .

Change code to:

 $('#s1 option[value=1]').hide(); $('#s1').val($('#s1 option').first().val()); 

Does work with new and old versions of jQuery work.

My question is, is there a shorter / more elegant way to do the same?

+5
javascript jquery
source share
2 answers
 $("#s1")[0].selectedIndex = 0; 

You can also do this if you really like jQuery:

 $("#s1").prop("selectedIndex", 0); 

See more details here: https://stackoverflow.com/a/414618/

+4
source share

Just do not set a value that automatically selects the first value and works in both versions:

 $('#s1 option[value=1]').remove(); //$('#s1').val(''); 

demo version: 1.9.1 and demo version: 1.10.1


According to your update and comments, you can use the following:

 $('#s1 option[value=1]').hide(); $('#s1 option[value=2]').hide(); $('#s1 option:visible').first().attr('selected', 'selected'); 

demonstration

+2
source share

All Articles