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 non-hidden option, after hiding some options, including the currently selected one.
Since jQuery 1.10+ the $('#s1').val('');
no longer selects the first non-hidden option, while .val(<some proper value for the particular select box>)
works ok.
Trying the following approaches does not help because both selectedIndex
and .first().val()
consider the hidden options:
$("#s1").prop("selectedIndex", 0);
$('#s1 option').first().prop('selected', true);
Next thing that comes to mind (also suggested by C-link) also does not work, because the :visible
selector does not work properly for select options.
$('#s1 option:visible').first().prop('selected', true);
Looking for some generic way (not depending on knowledge of what are the particular values and what options have been hidden) to achieve the same behaviour as $('#s1').val('');
in old jQuery.
Select first element of <select> element using JQuery selector. Use . prop() property to get the access to properties of that particular element. Change the selectedIndex property to 0 to get the access to the first element.
To achieve the best performance when using :visible to select elements, first select the elements using a pure CSS selector, then use . filter(":visible") . Using this selector heavily can have performance implications, as it may force the browser to re-render the page before it can determine visibility.
The :visible selector in jQuery is used to select every element which is currently visible. It works upon the visible elements. The elements that are consuming space in the document are considered visible elements. The height and width of visible elements are larger than 0.
Answer: Use the jQuery :visible Selector You can use the jQuery :visible selector to check whether an element is visible in the layout or not. This selector will also select the elements with visibility: hidden; or opacity: 0; , because they preserve space in the layout even they are not visible to the eye.
Shortly Like this:
$('#s1').find("option:not(:hidden):eq(0)");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With