JQuery how to choose the first option is not a hidden choice

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 select the first non-hidden option, hiding some parameters, including the currently selected one.

Since jQuery 1.10+ $('#s1').val(''); no longer selects the first non-hidden parameter, and .val(<some proper value for the particular select box>) works fine.

Trying to use the following approaches did not help, because both selectedIndex and .first().val() consider hidden parameters:

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

$('#s1 option').first().prop('selected', true);

The next thing that comes to mind (also suggested by C-link ) also does not work, because the :visible selector does not work properly for selecting options.

$('#s1 option:visible').first().prop('selected', true);

You are looking for some general way (independent of knowing which specific values ​​and which options were hidden) to achieve the same behavior as $('#s1').val(''); in old jQuery.

+7
javascript jquery html
source share
6 answers

Compiled from all the other answers / comments, the following:

 $('#s1 option').each(function () { if ($(this).css('display') != 'none') { $(this).prop("selected", true); return false; } }); 
+6
source share

In the near future:

 $('#s1').find("option:not(:hidden):eq(0)"); 
+7
source share

Try the following:

 <select id="s1"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> $('#s1 option[value=1]').hide(); var firstVisibleValue = ''; $('#s1').children().each(function(){ //iterate options //check if option is visible - if not set to display none, which is what `.hide` does. if($(this).css('display') != 'none'){ firstVisibleValue = $(this).val(); return false; //stop iterating } }); $('#s1').val(firstVisibleValue); 
+1
source share

Try this code

 $('#s1 option[value="1"]').hide(); $('#s1').find('option').each(function() { if($(this).is(':visible')) { $(this).attr("selected","selected"); return false; } }); 
0
source share

perhaps it:

 $('#s1').find("option:not([hidden]):eq(0)"); 
0
source share

You can easily do this using the class

 $('#s1 option[value=1]').hide(); $('#s1 option[value=1]').addClass('hidden'); $('#s1 option[value=1]').removeClass('visible') $('#s1').val(''); $('#s1 .visible:first').val(); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="s1"> <option class="visible" value="1">1</option> <option class="visible" value="2">2</option> <option class="visible" value="3">3</option> </select> 
0
source share

All Articles