8

I'm trying to hide some options from a drop down. JQuery's .hide() and .show() work great in Firefox and Chrome, but no luck in IE.

Any good ideas?

Tony Brasunas
  • 4,012
  • 3
  • 39
  • 51

3 Answers3

12

Hide and Show the Options based on Browser detection

Of many possible approaches, this method requires browser sniffing, which can be unstable, but on the other hand with this approach we don't have to swap in and out multiple copies of the same select list.

//To hide elements
$("select option").each(function(index, val){
    if ($(this).is('option') && (!$(this).parent().is('span')))
        $(this).wrap((navigator.appName == 'Microsoft Internet Explorer') ? '<span>' : null).hide();
});

//To show elements
$("select option").each(function(index, val) {
    if(navigator.appName == 'Microsoft Internet Explorer') {
        if (this.nodeName.toUpperCase() === 'OPTION') {
            var span = $(this).parent();
            var opt = this;
            if($(this).parent().is('span')) {
                $(opt).show();
                $(span).replaceWith(opt);
            }
        }
    } else {
        $(this).show(); //all other browsers use standard .show()
    }
});

Credit for this lies squarely with Dima Svirid here: http://ajax911.com/hide-options-selecbox-jquery/

Tony Brasunas
  • 4,012
  • 3
  • 39
  • 51
3

Just to mention that IE11 navigator.appName returns 'Netscape' :) So taking it into consideration:

$("select option[value='your_option_value']").wrap((navigator.appName == 'Microsoft Internet Explorer' || navigator.appName == 'Netscape') ? '<span>' : null).hide();
Vlado
  • 3,517
  • 2
  • 26
  • 24
  • 1
    This is a good point. However, other browsers can [choose to return 'Netscape' here too](http://stackoverflow.com/questions/14573881/why-does-javascript-navigator-appname-return-netscape-for-safari-firefox-and-ch), so your mileage may vary. – Tony Brasunas Apr 15 '17 at 19:07
0

I found a rather simple solution, although the options will not be hidden but disabled on IE.

$('#delivery_time option[value="06:30"]').removeAttr('disabled').show();       // To Show/Enable
$('#delivery_time option[value="06:30"]').attr('disabled', 'disabled').hide(); // To Hide/Disable

Here is the source where I stumbled upon these 2 lines: IT Support Guides - Internet Explorer – How to hide select options using jQuery

Rikj000
  • 27
  • 5