简体   繁体   中英

Search one table at a time from multiple tables with same class name

I've got some working js that searches a table based on text provided via an input element. Each table has its own input element. All tables have the same class name and so do all input elements. How do I use jquery to specify 'this' particular input should search only in the next table below it.

jquery

$(document).ready(function () {
  $(".searchTable").on("keyup", function () {

    var value = $(this).val().toLowerCase();

    $(".matchTable tr").filter(function () {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });

  });
});

html

<div class="pbTable">
    <div class="name">
      <input type="search" name="" value="" placeholder="SEARCH" class="searchTable">
    </div>

    <table class="matchTable">
      <thead>
        <tr>
          <th>heading</th>
          <th>heading</th>
          <th>heading</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>data</td>
          <td>data</td>
          <td>data</td>
        </tr>

      </tbody>
    </table>

  </div>
<div class="pbTable">
    <div class="name">
      <input type="search" name="" value="" placeholder="SEARCH" class="searchTable">
    </div>

    <table class="matchTable">
      <thead>
        <tr>
          <th>heading</th>
          <th>heading</th>
          <th>heading</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>data</td>
          <td>data</td>
          <td>data</td>
        </tr>

      </tbody>
    </table>

  </div>

Following should make it work

  $(".searchTable").on("keyup", function () {

    var value = $(this).val().toLowerCase();

    $(this).closest('.pbTable').find(".matchTable tr").filter(function () {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });

  });

You need to get current table by looking at the parent of the current input.

$(document).ready(function () {
  $(".searchTable").on("keyup", function () {

    var value = $(this).val().toLowerCase();
    var table = $(this.parentNode.parentNode).find('.matchTable')[0];

    $(table).find("tr").filter(function () {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });

  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM