Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery how to select the first non-hidden select option

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.

like image 986
bbonev Avatar asked Jun 27 '14 05:06

bbonev


People also ask

How do I get the first select option in jQuery selected?

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.

How do I get only visible elements in jQuery?

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.

Is visible selector jQuery?

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.

Which jQuery filter can be used to check if element is visible?

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.


1 Answers

Shortly Like this:

$('#s1').find("option:not(:hidden):eq(0)");
like image 157
israr Avatar answered Oct 01 '22 21:10

israr