Hide select option in IE using jQuery

Viewed 71178

Currently I am using jQuery to hide/show select options using following code.

$("#custcol7 option[value=" + sizeValue + "]").hide();

This works fine in Firefox, but doesnt do any good in other browsers. How to I hide options from select in Chrome, Opera and IE?

18 Answers

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.

Just deleted it and store it in a var in your JavaScript. You can just create the new object when you need it later.

Otherwise try the disabled attribute mentioned above.

In IE 11(Edge), the following code is working.

 $("#id option[value='1']").remove();

and to ad back,

$('<option>').val('1').text('myText').appendTo('#id');

meder's solution is what I went with for this, but with a small tweak to prevent it from wrapping an option in a span that was already in a span:

$.fn.hideOption = function() {
    this.each(function() {
        if (!$(this).parent().is('span')) {
            $(this).wrap('<span>').hide();
        }
    });
};
$.fn.showOption = function() {
    this.each(function() {
        var opt = $(this).find('option').show();
        $(this).replaceWith(opt);
    });
};
    <html>
    <head><script> 
    $(document).ready(function(){
    $("#l1").change(function(){
            var selectedId=$("#dl1 option[value='"+$(this).val()+"']").attr("id");
            $("#dl2 option[data-id ='"+selectedId+"']").removeAttr('disabled');
            $("#dl2 option[data-id !='"+selectedId+"']").attr('disabled','disabled');
            $("#l2").val("");
    });
    });
    </script></head>
    <body>
    <label for="l1">choose country</label>
    <input list="dl1" name="l1" id="l1" type='select'>
        <datalist id="dl1" name="dl1">
            <option value="India" id=1>
            <option value="US" id=2>
            <option value="Germany" id=3>
        </datalist>
    <br>
    <label for="l2">choose City</label>
    <input list="dl2" name="l2" id="l2" type='select'>
        <datalist id="dl2">
            <option value="New Delhi" id="11" data-id="1">
            <option value="Washington DC" id="12" data-id="2">
            <option value="Berlin" id="13" data-id="3">
            <option value="Mumbai"id="14" data-id="1">
            <option value="NewYork" id="15" data-id="2">
            <option value="Munich" id="16" data-id="3">
        </datalist>
    </body>
    </html>
Related