I've realized that Chrome, it seems, will not allow me to hide <option>
in a <select>
. Firefox will.
I need to hide the <option>
s that match a search criteria. In the Chrome web tools I can see that they are correctly being set to display: none;
by my JavaScript, but once then <select>
menu is clicked they are shown.
How can I make these <option>
s that match my search criteria NOT show when the menu is clicked? Thanks!
this one seems to work for me in chrome
For HTML5, you can use the 'hidden' attribute.
It is not supported by IE < 11. But if you need only to hide a few elements, maybe it would be better to just set the hidden attribute in combination with disabled in comparison to adding/removing elements or doing not semantically correct constructions.
Reference.
Simple answer: You can't. Form elements have very limited styling capabilities.
The best alternative would be to set
disabled=true
on the option (and maybe a gray colour, since only IE does that automatically), and this will make the option unclickable.Alternatively, if you can, completely remove the
option
element.I would suggest that you do not use the solutions that use a
<span>
wrapper because it isn't valid HTML, which could cause problems down the road. I think the preferred solution is to actually remove any options that you wish to hide, and restore them as needed. Using jQuery, you'll only need these 3 functions:The first function will save the original contents of the select. Just to be safe, you may want to call this function when you load the page.
This next function calls the above function to ensure that the original contents have been saved, and then simply removes the options from the DOM.
The last function can be used whenever you want to "reset" back to all the original options.
Note that all these functions expect that you're passing in jQuery elements. For example:
Here is a working example: http://jsfiddle.net/9CYjy/23/
!!! WARNING !!!
Replace the second "IF" by "WHILE" or doesn't work !
Select inputs are tricky in this way. What about disabling it instead, this will work cross-browser:
This will disable every-other
<option>
element, but you can select which ever one you want.Here is a demo: http://jsfiddle.net/jYWrH/
Note: If you want to remove the disabled property of an element you can use
.removeProp('disabled')
.Update
You could save the
<option>
elements you want to hide in hidden select element:You can then add the
<option>
elements back to the original select element:In these two examples it's expected that the visible select element has the id of
visible
and the hidden select element has the id ofhidden
.Here is a demo: http://jsfiddle.net/jYWrH/1/
Note that
.on()
is new in jQuery 1.7 and in the usage for this answer is the same as.bind()
: http://api.jquery.com/on