Home > Software design >  Filter table with JS and have a "No Results Found"
Filter table with JS and have a "No Results Found"

Time:09-23

I have been trying to work out how to incorporate a if else statement to the following code to return a add row to the table is results = 0 with a message that says "No Results Found". My code is:

//Function for searching products
$(document).ready(function(){
    $("#productInput").on("keyup", function() {
        let value = $(this).val().toLowerCase();
        $("#productTable tr").filter(function() {
            $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
        });

    });
});

Cheers

CodePudding user response:

After you toggle all the matching rows, count the number of visible rows. If it's 0, add the row that says nothing found.

filter() returns the set of elements that match the condition. You're not returning anything from the callback function, so you should use .each().

$(document).ready(function() {
  $("#productInput").on("keyup", function() {
    let value = $(this).val().toLowerCase();
    $("#productTable tr.notfound").remove(); // remove extra row if we added it during previous filter
    $("#productTable tr").each(function() {
      $(this).toggle($(this).text().toLowerCase().includes(value));
    })
    if ($("#productTable tr:visible").length == 0) {
      $("#productTable").append("<tr class='notfound'><td>No results found</td></tr>");
    }
  });
});

  • Related