Why Does My Jquery Filter Only Work Once On This Select Element?
Solution 2:
you are removing all elements that have a different class than the selected options value:
$("#product-multiple-2").empty().html(matches);
the line is effectively removing all options first, then adds the ones that matched on the line before.
you could instead hide everything: (approximately)
$("#product-multiple-2 option").hide();
matches.show();
Solution 3:
When you do the first empty()
, you don't have any other options any more, only the red ones.
So, for example, when you run it for the first time, selecting Red on select1, you get only the red options in select 2 - FOREVER!
When you run the second time, Green for example, there are no Green options in select2, so you get an empty nodelist.
you should use jQuery's hide() and show(), like this:
$("#product-multiple-1").change(function(){
var matches = $("#product-multiple-2 option." + $(this).val());
$("#product-multiple-2 option").not('.'+ $(this).val()).css('display', 'none');
matches.css('display', 'block'))
return matches;
});
Solution 4:
It's because you are removing the items that don't match so when you select a different colour, the items for that colour are gone.
Save the originals and reload them instead like this:
var productMultiple2 = $("#product-multiple-2");
productMultiple2.data('originalOptions', productMultiple2.html());
$("#product-multiple-1").change(function(){
varval = $(this).val();
productMultiple2.html(productMultiple2.data('originalOptions'));
if (val !== "Choose Option") {
$("#product-multiple-2 > option").filter(function() {
return !$(this).is("." + val) && $(this).val() !== "Choose Option";
}).remove();
}
});
Fixed to not break with "Choose Option"
Solution 5:
The reason this is happening is because you're removing all the options from the second select tag in order to display the ones with a class that matches the first select's value.
There's two (maybe more?) things you can do:
You can keep a copy of the option elements in a variable and then grab the elements you want like so:
var $options = $("#product-multiple-2 > option"); $("#product-multiple-1").change(function(){ var $matches = $options.filter("." + $(this).val()); $("#product-multiple-2").empty().html($matches); console.log($matches); });
You can disable the options that are not available in the second select like so:
$("#product-multiple-1").change(function(){ $("#product-multiple-2 > option").each(function(index, elem) { if ($(elem).is("." + $(this).val())) { elem.disabled = false; } else { elem.disabled = true; } }); console.log($matches); });
Post a Comment for "Why Does My Jquery Filter Only Work Once On This Select Element?"