Live search на javascript

215
27 мая 2017, 15:44

Нашел такой код на jsfiddle:

$("#search").on("keyup", function() { 
  var value = $(this).val(); 
 
  $("table tr").each(function(index) { 
    if (index !== 0) { 
 
      $row = $(this); 
 
      var id = $row.find("td:first").text(); 
 
      if (id.indexOf(value) !== 0) { 
        $row.hide(); 
      } else { 
        $row.show(); 
      } 
    } 
  }); 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
<table> 
  <tr> 
    <th>Unique ID</th> 
    <th>Random ID</th> 
  </tr> 
  <tr> 
    <td>214215</td> 
    <td>442</td> 
  </tr> 
  <tr> 
    <td>1252512</td> 
    <td>556</td> 
  </tr> 
  <tr> 
    <td>2114</td> 
    <td>4666</td> 
  </tr> 
  <tr> 
    <td>3245466</td> 
    <td>334</td> 
  </tr> 
  <tr> 
    <td>24111</td> 
    <td>54364</td> 
  </tr> 
</table> 
<br /> 
<input type="text" id="search" placeholder="  live search"></input>`

Скрипт работает, все нормально, но как сделать чтоб по началу данные таблицы не отображались а начали отображаться после того как пользователь начинает набирать текст?

Answer 1

С самого начала можно скрывать все <tr>, которые находятся в <tbody>, а заголовочные ячейки объединить в <thead>.

$("#table-for-search tbody tr").hide(); 
 
$("#search").on("keyup", function() { 
  var value = $(this).val(); 
 
  $("table tr").each(function(index) { 
    if (index !== 0) { 
 
      $row = $(this); 
 
      var id = $row.find("td:first").text(); 
 
      if (id.indexOf(value) !== 0) { 
        $row.hide(); 
      } else { 
        $row.show(); 
      } 
    } 
  }); 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
<table id=table-for-search> 
  <thead> 
    <tr> 
      <th>Unique ID</th> 
      <th>Random ID</th> 
    </tr> 
  </thead> 
  <tr> 
    <td>214215</td> 
    <td>442</td> 
  </tr> 
  <tr> 
    <td>1252512</td> 
    <td>556</td> 
  </tr> 
  <tr> 
    <td>2114</td> 
    <td>4666</td> 
  </tr> 
  <tr> 
    <td>3245466</td> 
    <td>334</td> 
  </tr> 
  <tr> 
    <td>24111</td> 
    <td>54364</td> 
  </tr> 
</table> 
<br /> 
<input type="text" id="search" placeholder="  live search">

READ ALSO
Не отображаются svg иконки в safari

Не отображаются svg иконки в safari

Использую svg спрайт вида

522
HTML и HTML5, CSS и CSS3

HTML и HTML5, CSS и CSS3

HTML2 и HTML5 - это один и тот же язык, HTML, просто разные версии (2 и 5), или же это принципиально разные языки разметки? Как будет правильно назвать...

215