Hide options in select element, not working in IE?

2019-06-16 05:20发布

问题:

Possible Duplicate:
Hide select option in IE using jQuery

So as you can see below, i have two select elements. The first one has two values, 1.4 and 1.7. Depending on which option is selected i want to disable certain options in the second select element. It works perfectly fine in chrome, but IE is being a bitch (as usual!).

Any ideas what's wrong?

<p>
    <label style="width: 155px; display: inline-block;">Height</label>
    <select name="height">
        <option value="1.4">1.4</option>
        <option value="1.7">1.7</option>
    </select>
</p>
<p>
    <label style="width: 155px; display: inline-block;">Amount</label>
    <select name="slanor">
        <option class="four" value="2">2</option>
        <option class="four seven" value="3">3</option>
        <option class="seven" value="4">4</option>
    </select>
</p>


<script>
$(document).ready(function() {
    check();

    $('select[name=height]').change(function() {
        check();
    });

    function check() {
        var slanor = $('select[name=slanor]');
        var currHeight = $('select[name=height]').val();

        if(currHeight == '1.4') {
            slanor.find('option').hide();
            slanor.find('.four').show();
        } else {
            slanor.find('option').hide();
            slanor.find('.seven').show();
        }
    }
});
</script>

回答1:

The notion of hidden options in a select doesn't exist in IE. You would have to manually remove and re-add the entries, which may be somewhat of an inconvenience.

Another solution would be to also disable the elements:

slanor.find(option).hide().prop('disabled', true);

This will hide the option in all browsers that support it, but disable it in IE, which means it'll still be visible, but visually distinguished from the other options, and un-selectable.

However: if your problem is exactly as you have described, and there are only two options that your script will vary on, the simplest solution might be to hide and show two different dropdowns entirely, depending on which option is selected.



回答2:

Calling .hide() in jQuery adds display:none to the element. I doubt that it is standard HTML that you can hide options in this way.

You could use this code instead:

slanor.empty();
if (currHeight == '1.4') {
    slanor.append($('<option'>).val('2').text('2'));
    slanor.append($('<option'>).val('3').text('3'));
}
else {
    slanor.append($('<option'>).val('3').text('3'));
    slanor.append($('<option'>).val('4').text('4'));
}


回答3:

The option tag doesn't support the css display attribute. Which is what show()/hide() does. Your best bet is to either remove and recreate the options as they are needed. Or I guess you could append them to another hidden object and pull them back when you need them fully formed.

So you would have something like

$("option").appendTo($("#myhiddenselect"));
$(".four").appendTo($("#myvisibleselect"));