5

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 behind this code is to select the first option.

After 1.10, the $('#s1').val(''); part is no longer working in the same way. I suppose that it was never meant to be used that way but its old code and have to be modernized in some way...

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

Changing code to:

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

Does the job with both new and old jQuery versions.

My question is if there is shorter/more elegant way to do the same thing?

bbonev
  • 1,406
  • 2
  • 16
  • 33

2 Answers2

4
$("#s1")[0].selectedIndex = 0;

You can also do this if you really like jQuery:

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

More here: https://stackoverflow.com/a/1314266/283863

Community
  • 1
  • 1
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
  • both does not work, if the first option is hidden; anyways selected your answer as most close... – bbonev Jun 27 '14 at 05:26
2

Just don't set the value it selects first value automatically and works in both versions:

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

demo version: 1.9.1 and demo version: 1.10.1


As per your update and comments, you can use like this:

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

demo

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
  • +1 because you are right for .remove but the problem is with .hide – bbonev Jun 27 '14 at 04:11
  • how about this? http://jsfiddle.net/Ngaqk/4/ – Bhojendra Rauniyar Jun 27 '14 at 04:16
  • yep, it works but i need generic way, because the first visible option is not known in advance – bbonev Jun 27 '14 at 04:23
  • 1
    then you should use as Darek http://jsfiddle.net/Ngaqk/5/ – Bhojendra Rauniyar Jun 27 '14 at 04:25
  • http://jsfiddle.net/979HZ/2/ - check this, the selectedIndex property counts hidden items too – bbonev Jun 27 '14 at 04:30
  • Still does not work ok - it displays 1, while this option is hidden. The problem with all approaches above is that both selected index and .first() also return and count hidden options. I am going to ask a new question with more properly formulating the problem itself – bbonev Jun 27 '14 at 04:44
  • in more refined way here: http://stackoverflow.com/questions/24444264/jquery-how-select-the-first-non-hidden-select-option – bbonev Jun 27 '14 at 05:02