Search code examples
jquerytextboxmessagebox

Return message - no results from text box


I'm very new to jquery and looking to learn.

I'm trying to develop a search page. At present nothing is returned if there is no match. I've tried various snippets to add add a message but it doesn't seem to work.

Could anyone help?

Thanks

 <input type="text" id="search-criteria"/><BR> 
 <input type="button" id="search" value="Policy Search"/><BR> 
 <div  class="contact-name" style='background-color:#f2f2f2'> Daniel </div> 
 <div class="contact-name" style='background-color:#f2f2f2'>david </div>



$('.contact-name').hide();
$('#search').click(function(){
$('.contact-name').hide();
var txt = $('#search-criteria').val();
$('.contact-name').each(function(){
   if($(this).text().toUpperCase().indexOf(txt.toUpperCase()) != -1){
       $(this).show();
   }
});
});

Solution

  • You need to check if the .each loop found a value; if it did, then exit early; if not, show the "no results" message.

    <!-- Add this element to the HTML. -->
    <div class="no-results">There are no results available.</div>
    
    $(".contact-name, .no-results").hide();
    $("#search").click(function() {
      $(".contact-name, .no-results").hide();
      var txt = $("#search-criteria").val();
      var found = false;
      $(".contact-name").each(function() {
        if ($(this).text().toUpperCase().indexOf(txt.toUpperCase()) != -1) {
          $(this).show();
          found = true;
          return false;
        }
      });
      if (!found) {
        $('.no-results').show();
      }
    });