Home > Enterprise >  Search in Html-table (in Td Specific Child Tag) and Hide Row
Search in Html-table (in Td Specific Child Tag) and Hide Row

Time:07-09

I want the table to be searched only in the H3 tag, not TD tag. And if a result is found, its TR should be hidden -h3 is a Child tag under TD.

for Example:

<tr>
  <td>
    <h3>Hier</h3>
    <div></div>
  </td>
</tr>

<script>
$(document).ready(function(){
        $("#myInput").on("keyup", function() {
            const value = $(this).val().toLowerCase();
            $("#myTable tr").filter(function() {
                $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
            });
            console.log(value);
        });
    });
</script>

Thank you For Help

CodePudding user response:

The main issue in your code is because you're searching through the text of the tr as a whole. You need to call find('h3') and then compare to the text in that element.

Also note that filter() is intended to do just that; filter a collection of elements and return a subset of them. You shouldn't call toggle() within it. Instead call hide(), filter to find matches, then show() them.

jQuery($ => {
  $("#search").on('input', e => {
    const value = $(e.target).val().toLowerCase().trim();
    $("table tr").hide()
      .filter((i, tr) => $(tr).find('h3').text().toLowerCase().indexOf(value) > -1).show();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<input type="text" name="search" id="search" />
<table>
  <tr>
    <td>
      <h3>Foo</h3>
      <div></div>
    </td>
  </tr>
  <tr>
    <td>
      <h3>Foo bar</h3>
      <div></div>
    </td>
  </tr>
  <tr>
    <td>
      <h3>Hier</h3>
      <div></div>
    </td>
  </tr>
</table>

  • Related