'Display "No Results" message with jQuery checkbox filter
I found a jQuery filter that works really well for my needs (http://jsfiddle.net/n3EmN/171/). My only issue is that I want it to display a "No results found" message when the filtered results do not produce a result.
var $filterCheckboxes = $('input[type="checkbox"]');
$filterCheckboxes.on('change', function() {
var selectedFilters = {};
$filterCheckboxes.filter(':checked').each(function() {
if (!selectedFilters.hasOwnProperty(this.name)) {
selectedFilters[this.name] = [];
}
selectedFilters[this.name].push(this.value);
});
// create a collection containing all of the filterable elements
var $filteredResults = $('.flower');
// loop over the selected filter name -> (array) values pairs
$.each(selectedFilters, function(name, filterValues) {
// filter each .flower element
$filteredResults = $filteredResults.filter(function() {
var matched = false,
currentFilterValues = $(this).data('category').split(' ');
// loop over each category value in the current .flower's data-category
$.each(currentFilterValues, function(_, currentFilterValue) {
// if the current category exists in the selected filters array
// set matched to true, and stop looping. as we're ORing in each
// set of filters, we only need to match once
if ($.inArray(currentFilterValue, filterValues) != -1) {
matched = true;
return false;
}
});
// if matched is true the current .flower element is returned
return matched;
});
});
$('.flower').hide().filter($filteredResults).show();
});
If you use the Fiddle to select both "Red" and "Africa", the results show blank. An ideal UX would be to say "No results found, try changing your filters."
How can I accomplish this with the provided code?
Solution 1:[1]
Add the css class for hide
.hide{display:none; }
Add this div at the bottom of all your .flowers div
<div id="NoResult" class="hide" >No results found, try changing your filters.</div>
Add this inside your change event
if(!$('.flower').is(':visible'))
{
$("#NoResult").removeClass("hide");
}
else
{
$("#NoResult").addClass("hide");
}
Here is the altered fiddle : http://jsfiddle.net/r97L1zvf/1/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Vidiya Prasanth Pappannan |
