Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I hide select options with JavaScript? (Cross browser)

This should work:

$('option').hide(); // hide options 

It works in Firefox, but not Chrome (and probably not in IE, not tested).

A more interesting example:

<select>     <option class="hide">Hide me</option>     <option>visible option</option> </select> <script type="text/javascript"> // try to hide the first option $('option.hide').hide();  // to select the first visible option $('option:visible').first().attr('selected', 'selected'); </script> 

Or see the example at http://jsfiddle.net/TGxUf/

Is the only option to detach the option elements from the DOM? I need to show them again later, so this would not be very effective.

like image 977
dave1010 Avatar asked Dec 09 '10 13:12

dave1010


People also ask

How do I hide a selection option?

You can specify either 'hidden' (without value) or 'hidden="hidden"'. Both are valid. A hidden <option> element is not visible, but it maintains its position on the page. Removing the hidden attribute makes it re-appear.

How do you hide a selection in HTML?

You can specify either 'hidden' (without value) or 'hidden="hidden"'. Both are valid. A hidden <select> element is not visible, but it maintains its position on the page.

How do you hide the selection on safari?

$(this). prop("disabled", true); // for safari $(this). hide(); This way options will be hidden in most browsers.

How do I change an HTML selected option using JavaScript?

In order to change the selected option by the value attribute, all we have to do is change the value property of the <select> element. The select box will then update itself to reflect the state of this property.


1 Answers

Unfortunately, you can't hide option elements in all browsers.

In the past when I have needed to do this, I have set their disabled attribute, like so...

$('option').prop('disabled', true); 

I've then used the hiding where it is supported in browsers using this piece of CSS...

select option[disabled] {     display: none; } 
like image 84
alex Avatar answered Oct 21 '22 13:10

alex