Hide select option in IE using jQuery

I just came across this and instead of cloning the entire select over and over I just replaced the options that need to be hidden with span elements and hiding the spans ( though the browser didnt visually show them anyway, I think ) - you may need to change your code ( if complex ) to iterate through the spans for complex logic.

The spans store a reference to the option and replace themselves with it when they need to be shown.

This code can obviously be refactored and prettified.

http://fiddle.jshell.net/FAkEK/12/show/

EDIT #2 ( USE THIS INSTEAD ): It occurred to me that instead of doing all this clone/reference/replace crap, just wrap the option with a span, hide the span, and on show just replace the span with the option again..

http://fiddle.jshell.net/FAkEK/25/show/


I think meder has provided valid answer and here it is slightly changed to reflect what works for me:

$.fn.optVisible = function( show ) {
    if( show ) {
        this.filter( "span > option" ).unwrap();
    } else {
        this.filter( ":not(span > option)" ).wrap( "<span>" ).parent().hide();
    }
    return this;
}

Tested with (long live BrowserStack):

  • Windows XP: IE 6.0, Firefox 3.0, Safari 4.0, Opera 10.0, Chrome 14.0
  • Windows 8: IE 10.0 Metro
  • iOS 3.2 (iPad), iOS 6.0 (iPhone 5)
  • Android 1.6 (Sony Xperia X10)

jsfiddle


You don't, it's not supported in IE (and assumably not in Chrome or Opera either). You would have to remove the options altogether and add them back later if you want them to be truly invisible. But in most cases a simple disabled="disabled" should suffice and is a heck of a lot simpler than handling the removing and adding of options.


try detach(). you can reattach it later if needed using append() or insertAfter()