Search through Table Cells

Viewed 44

I have a table which is hidden which contains 1272 rows and within it 3 columns with a

  1. Store Name
  2. Postcode
  3. Button

The script is meant to search for all td cells for either a store name or a postcode and is not returning the desired results.

This is a link to the search

Advice appreciated

$("#searchterm").on("keyup", function() {
    var value = $.trim($(this).val().toLowerCase());


    $("table#participating_stores tr:gt(0)").each(function(index) {
        if (index !== 0) {
            $row = $(this);
            
            var $tdElement = $row.find("td");
            var id = $.trim($tdElement.text().toLowerCase()) 

            var matchedIndex = id.indexOf(value);
            
            if (matchedIndex != 0) {
                $row.hide();
            }
            else {
                //highlight matching text, passing element and matched text
      
                $row.show();
            }
        }
    });
});
1 Answers

I think this is what you are looking for. I've made this runnable snippet which hopefully makes things more clear for you and anyone else trying to think about this problem.

$("#searchterm").on("keyup", function() {
  var value = $(this).val();

  $("table tr:not(:first)").show().filter(function(index) {
      return $(this).find("td").text().indexOf(value) == -1;
  }).hide();
});
table, tr, td, th{
    border: 1px solid black;
    padding: 3px;
}

table th{
    background-color: #dddddd;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
    <tr><th>Postal Code</th><th>Store Name</th></tr>
    <tr><td>12345</td><td>store name</td></tr>
    <tr><td>99999</td><td>another store name</td></tr>
    <tr><td>54321</td><td>yet another name</td></tr>
    <tr><td>34343</td><td>4th name</td></tr>
    <tr><td>87898</td><td>fifth name</td></tr>
</table>
<br />
<input type="text" id="searchterm" placeholder="search"></input>

Related