Reputation: 1025
I'm currently building a page where a search field acts as a filter, just as follow :
// Custom case insensitive selector
jQuery.expr[':'].Contains = function(a,i,m) {
return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0;
};
// Search field filter
var $section = $('section');
$('#search').keyup(function() {
var input = $(this).val();
if(input) {
$section.hide();
$("section:Contains('"+input+"')").show();
}
else {
$section.show();
}
});
It works perfectly fine, but there is one issue that I'd like to solve. When the entered string is not found in all the existing <section>
, the page remains blank.
My question is then quite simple, how could I display a default message on my page when no results are found by the filter? Something like a simple <p>
explaining that "no results were found".
The idea is to display it only once as long as the string is not found.
Thanks for your help.
Upvotes: 0
Views: 4602
Reputation: 1025
I ended up doing the following thing :
Creating my error message at the end of the list.
<p id="noresults">Error message.</p>
Showing/hiding it when needed.
// Search field filter
var $section = $('section');
var $noresults = $('#noresults');
$noresults.hide();
$('#search').bind('keyup', function() {
var input = $(this).val();
if(input) {
$section.hide();
var result = $("section:Contains('"+input+"')");
if(result.length) {
$noresults.hide();
result.show();
} else {
$noresults.show();
}
}
else {
$noresults.hide();
$section.show();
}
});
Upvotes: 4
Reputation:
Check the length of matched elements first.
var elements = $("section:Contains('"+input+"')");
if(elements.length) //Found
elements.show();
else
//display a message
$("body").append("<p>No results were found.</p>");
Upvotes: 1