noclist
noclist

Reputation: 1819

Hiding select options in IE with jQuery

I have 2 select lists, picking an option from the first one determines the options available in the second. This works great in Chrome, however IE is having trouble hiding the appropriate options on change of the first select. The hidden class is being applied, but the options are still visible. Any idea how to modify this to work in IE?

Fiddle

$(document).on('change', '#category', function(e) {
  if ($(this).prop('selectedIndex') == 0) {
    $('#condition option').addClass('hidden');
    $('#condition .cat-1').removeClass('hidden');
  } else if ($(this).prop('selectedIndex') == 1) {
    $('#condition option').addClass('hidden');
    $('#condition .cat-2').removeClass('hidden');
  }
});
.hidden {
  display: none !important;
}

#category {
  height: 40px;
}

#condition {
  height: 110px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="category" size="2">
  <option class="cat-1">Group 1</option>
  <option class="cat-2">Group 2</option>
</select>

<select id="condition" size="2">
  <option class="cat-1">Item from group 1</option>
  <option class="cat-1">Item from group 1</option>
  <option class="cat-1">Item from group 1</option>
  <option class="cat-2">Item from group 2</option>
  <option class="cat-2">Item from group 2</option>
  <option class="cat-2">Item from group 2</option>
</select>

Upvotes: 2

Views: 937

Answers (1)

Vadim Ovchinnikov
Vadim Ovchinnikov

Reputation: 14012

You can save select options to variable, then remove and readd any of them you want.

// saving options
var options = $("#condition option");

$(document).on('change', '#category', function(e) {
  if ($(this).prop('selectedIndex') == 0) {
    // deleteing all options
    $("#condition").empty();
    // adding options only of class .cat-1
    options.filter(".cat-1").each(function() {
      $("#condition").append($(this));
    });
  } else if ($(this).prop('selectedIndex') == 1) {
    // deleteing all options
    $("#condition").empty();
    // adding options only of class .cat-2
    options.filter(".cat-2").each(function() {
      $("#condition").append($(this));
    });
  }
});
#category {
  height: 40px;
}

#condition {
  height: 110px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="category" size="2">
  <option class="cat-1">Group 1</option>
  <option class="cat-2">Group 2</option>
</select>

<select id="condition" size="2">
  <option class="cat-1">Item from group 1</option>
  <option class="cat-1">Item from group 1</option>
  <option class="cat-1">Item from group 1</option>
  <option class="cat-2">Item from group 2</option>
  <option class="cat-2">Item from group 2</option>
  <option class="cat-2">Item from group 2</option>
</select>

Upvotes: 1

Related Questions