I have a real-time question filter with JQuery , it works perfectly, but when there are no search results I need to add a message that says so, eg. 'There are no results for your question'
How can I do it?
.hidden {display:none;}
<script src="https://code.jquery.com/jquery-3.5.0.min.js"></script>
<input type="text" id="search-project" name="search-project" placeholder="intenta: ¿Como hago mi primera compra?">
<ul class="list-porject">
<li>¿Como puedo fíar un producto?</li>
<li>¿Puedo vender mis productos?</li>
<li>¿Que se puede vender?</li>
<li>¿Existe la posibilidad de comprar sin tarjeta?</li>
</ul>
<script>
(function($){
$(document).ready(function() {
$("#search-project").keyup(function(){
// Retrieve the input field text and reset the count to zero
var filter = $(this).val();
// Loop through the comment list
$(".list-porject li").each(function(){
// If the list item does not contain the text phrase fade it out
if ($(this).text().search(new RegExp(filter, "i")) < 0) {
$(this).addClass('hidden');
} else {
$(this).removeClass('hidden');
}
});
});
})
})(jQuery)
</script>
You can create the message in the html and have it hidden by default. And display it when there is no match.
I have created a local variable to know if there has been a match or not. And I always check if the message is visible because it is hidden.
Hello, this has been my solution, you will see I have created a paragraph element that I have also put the hidden class on. Then when you add the hidden class to the list items I loop back through the li items and add 1 to a counter variable. Once it finishes running, it exits and compares the counter with the li elements that exist and if the counter is greater, I show the message.
I hope it helps you.
You could create an element where to have the message
No hay resultados.
. Then, depending on whether the amount ofli
is equal to the amount ofli.hidden
, then that element would have to be displayed.Example: