Reputation: 2530
This function allows users to filter products by color (using data-attributes
). How can I modify it to accommodate more than one value?
I'd like the function to return all items matching any of the data-attribute's values, and revert to the stricter criteria of the remaining filters when one of the filters is removed (by either unchecking the specific value or all color values). I've posted a fiddle with a simple example of the function here: http://jsfiddle.net/chayacooper/WZpMh/21/. The fiddle currently has the data-attributes
inside <li>
tags, but I'd like to use checkboxes in order to allow for multiple selections.
Edit - Products can have more than value in data-color (i.e. Black , White) indicating that it's available in either color, and can be multi-colored (i.e. Black & White).
I'm assuming that instead of $(this).data('color')
I should use something like $('input:checkbox:checked').data('color')
, but I'm not sure how to structure it.
$(document).ready(function () {
$('#attributes-Colors *').click(function () {
var attrColor = $(this).data('color');
$('#attributes-Colors').removeClass('active');
$(this).parent().addClass('active');
if (attrColor == 'All') {
$('#content').find('*').show();
} else {
$('#content').find('li:not([data-color="' + attrColor + '"])').hide();
$('#content').find('[data-color ~="' + attrColor + '"]').show();
}
return false;
});
});
Upvotes: 2
Views: 135
Reputation: 45155
Here's one way to do it:
I didn't add any handling for the "all colors" link, but that should be easy enough to do
var selected = [];
$('#attributes-Colors *').click(function () {
var attrColor = $(this).data('color');
var $this = $(this);
if ($this.parent().hasClass("active")) {
$this.parent().removeClass("active");
selected.splice(selected.indexOf(attrColor), 1);
} else {
$this.parent().addClass("active");
selected.push(attrColor);
}
$("#content").find("*").hide();
$.each(selected, function (index, item) {
$('#content').find('[data-color ~="' + item + '"]').show();
});
return false;
});
The basic idea is to keep an array of the selected colors and any time one of your color buttons is clicked, you will hide all the items and then reshow those that match all the colors in your selected
array.
For the all colors
you can simply add some extra logic to blank all the others and make all you items visible.
Upvotes: 1