0

Learner here! I'm trying to create a (name) search for an html table with a list of people. I've given each row in the table body an id of row-body and a data-attribute of data-name. For each row, I want to check if the search text can be found in the name, and if so, the row should show. Otherwise, the row should hide. Here's my code. How can I implement the if/else?

    $("#search-box").on('keyup', function () {

        const search = $("#search-box").val();

        $("#body-row").forEach($("#body-row"), if (CheckMatch($(this).data("name"), search)) {
            $(this).show();
        }
        else {
            $(this).hide();
        })

    function CheckMatch(n, s) {
        const name = n.toLowerCase();
        const search = s.toLowerCase();
        return name.includes(search);
    }
1
  • No, you can't pass an if statement around. You must pass a callback function. Of course you may put if/else inside that function. Notice however that it's in most cases much easier to use for … of loops than forEach. Commented Nov 2, 2020 at 4:57

2 Answers 2

2

The first thing to do would be to use classes instead of IDs - duplicate IDs in a single document is invalid HTML.

While you could do it just by writing a proper callback (using the proper name, .each - .forEach is for arrays and Sets and Maps, not jQuery objects):

$(".body-row").each(function() {
  if (CheckMatch($(this).data("name"), search)) {
    $(this).show();
  } else {
    $(this).hide();
  }
});

It'd be easier to use .toggle:

$(".body-row").each(function() {
    $(this).toggle(CheckMatch($(this).data("name"), search));
});
Sign up to request clarification or add additional context in comments.

Comments

0

A small snippet for other SO users to understand the question and solution easily.

$("#search-box").on("keyup", function() {

  let searchVal = $("#search-box").val();
  $(".list-item").each(function() {
    if (checkMatch(searchVal, $(this).text())) {
      $(this).show();
    } else {
      $(this).hide();
    }

    // $(this).toggle(checkMatch(searchVal, $(this).text()))
  });
});


function checkMatch(val, item) {
  return item.toLowerCase().includes(val.toLowerCase());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="search-box">

<ul>
  <li class="list-item">Apple</li>
  <li class="list-item">Mango</li>
  <li class="list-item">Banana</li>
  <li class="list-item">Berry</li>
  <li class="list-item">Appricot</li>
  <li class="list-item">Grapes</li>
  <li class="list-item">Guava</li>
  <li class="list-item">Watermelon</li>
  <li class="list-item">Melon</li>
  <li class="list-item">Pineapple</li>
</ul>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.