I am using the following code to filter my results by using checkboxes. It displays the results which have checked items in common:
$('input').change(function() {
var room_array = new Array(),
loc_array = new Array();
$('.br').each(function() {
if ($(this).is(':checked')) {
room_array.push($(this).data('bedrooms'));
}
});
$('.loc').each(function() {
if ($(this).is(':checked')) {
loc_array.push($(this).data('location'));
}
});
//console.log(loc_array, room_array);
$('li').each(function() {
if ($.inArray($(this).data('location'), loc_array) > -1 && $.inArray($(this).data('bedrooms'), room_array) > -1) {
$(this).show();
} else {
$(this).hide();
}
});
});
<input data-bedrooms="1" class="br" type="checkbox">1 bedroom<br>
<input data-bedrooms="2" class="br" type="checkbox">2 bedrooms<br>
<input data-bedrooms="3" class="br" type="checkbox">3 bedrooms<br><br>
<input data-location="london" class="loc" type="checkbox">london<br>
<input data-location="new-york" class="loc" type="checkbox">new york<br>
<input data-location="paris" class="loc" type="checkbox">paris<br><br>
<ul>
<li data-bedrooms="1" data-location="paris">1 bedroom apartment paris</li>
<li data-bedrooms="1" data-location="paris">1 bedroom apartment</li>
<! -- similar combinations -->
<li data-bedrooms="2" data-location="new-york">2 bedroom apartment new yor</li>
</ul>
The problem is that when only 1 type of checkbox is selected, the results for that checkbox don’t display.
However, I want to allow the selection of only one type, e.g. either the number of bedrooms or the location. How can I achieve this?
Replace
With
To accept any value for a group when that group has no checked checkboxes.
By the way, your fiddle had two entries for
I changed one of them to
londonas your first example suggested.jsFiddle