Hiding <option> s in IE

I wrote this great function to filter select boxes when their value changed ...

$.fn.cascade = function() {
    var opts = this.children('option');
    var rel = this.attr('rel');
    $('[name='+rel+']').change(function() {
        var val = $(this).val();
        var disp = opts.filter('[rel='+val+']');
        opts.filter(':visible').hide();
        disp.show();
        if(!disp.filter(':selected').length) {
            disp.filter(':first').attr('selected','selected');
        }
    }).trigger('change');
    return this;
}

      

It looks at a property rel

, and if the element denoted by a symbol rel

changes, then it filters the list to only display parameters that have that value ... for example, it works with HTML that looks like this:

<select id="id-pickup_address-country" name="pickup_address-country">
  <option selected="selected" value="CA">Canada
  </option>
  <option value="US">United States
  </option>
</select>

<select id="id-pickup_address-province" rel="pickup_address-country" name="pickup_address-province">
  <option rel="CA" value="AB">Alberta
  </option>
  <option selected="selected" rel="CA" value="BC">British Columbia
  </option>
  <option rel="CA" value="MB">Manitoba
  </option>...
</select>

      

However, I just found that it doesn't work as expected in IE (of course!), Which doesn't seem to let you hide options

. How can I get around this?


Here's what I have:

(function($) {
    $.fn.cascade = function() {
        var filteredSelect = $(this);
        var filteredOpts = this.children('option');
        var triggerSelect = $('[name='+this.attr('rel')+']');

        triggerSelect.change(function() {
            var triggerValue = $(this).val();

            filteredOpts.detach()
                .filter('[rel='+triggerValue+']').appendTo(filteredSelect)
                .filter(':first').attr('selected','selected');
        }).trigger('change');
        return this;
    }
})(jQuery);

      

Which works in IE but still has two problems. The bit .filter(':first').attr('selected','selected');

doesn't seem to do anything in IE (it has to select the first visible item). Since I used it appendTo

, it is currently the last used by default. Another problem is that since I disable all elements immediately, you cannot have defaults in your HTML.

+2


a source to share


1 answer


Parameters cannot be marked as hidden. You have to use SelectElement.add (option) and SelectElement.remove (index) ...

Here is a link to remove and add options in the same order. How do I restore the order of the (incomplete) select list to its original order?



Here is the link where I made the post, just doing the simplest thing How to hide optgroup / option elements?

Notice in my post try catch. This is necessary when adding elements, especially when building a site in Firefox and IE.

+2


a source







All Articles