2017-04-26 87 views
0

嗨,我需要使用表中的jquery進行搜索。但問題是我的代碼只搜索所有行的第一個元素,而不是搜索整個表並顯示結果。我怎樣才能搜索整個桌子?用表查找表查詢

這裏是我的jQuery代碼

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

    $(".table tr").each(function(index) { 
     if (index !== 0) { 

      $row = $(this); 

       var id = $row.find("td").text(); 

      if (id.indexOf(value) !== 0) { 
       $row.hide(); 
       </td>'); 
      } 
      else { 
       $row.show(); 

      } 
     } 


    }); 
}); 

這裏是我的HTML表格:

<input type="text" class="form-control" name="search" id="search" placeholder="Search Records"> 
<table class="table table-bordered table-striped" id="employees"> 
         <thead> 
         <tr> 
          <th>No</th> 
          <th>Type</th> 
          <th>Name</th> 
          <th>Temp Address</th> 
          <th>Permanent Address</th> 
          <th>Mobile</th> 
          <th>Home</th> 
          <th>Update</th> 
         </tr> 
         </thead> 
         <tbody><tr> 

       <td>27006</td> 
       <td>Fixer</td> 
       <td>Sam</td> 
       <td>testing address</td> 
       <td></td> 
       <td>123456</td> 
       <td>123456</td> 
      </tr> 
      </tbody> 
      <tbody><tr> 

       <td>test</td> 
       <td>test</td> 
       <td>test</td> 
       <td>test</td> 
       <td>test</td> 
       <td>test</td> 
       <td>test</td> 
      </tr> 
      </tbody> 
      </table> 
+0

嘿,$(「#search」)id在你的html中的位置?如果你可以編寫代碼片段,那就太好了。 – Harsheet

+0

它的輸入類型放在表格上 Abbasi

+0

爲什麼重新發明輪子?使用https://datatables.net/ – funcoding

回答

3

試試這個 -

$("#search").keyup(function(){ 
 
     _this = this; 
 
     $.each($("#employees tbody tr"), function() {   
 
     if($(this).text().toLowerCase().indexOf($(_this).val().toLowerCase()) === -1) 
 
       $(this).hide(); 
 
      else 
 
       $(this).show();     
 
     }); 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" class="form-control" name="search" id="search" placeholder="Search Records"> 
 
<table class="table table-bordered table-striped" id="employees"> 
 
        <thead> 
 
         <tr> 
 
          <th>No</th> 
 
          <th>Type</th> 
 
          <th>Name</th> 
 
          <th>Temp Address</th> 
 
          <th>Permanent Address</th> 
 
          <th>Mobile</th> 
 
          <th>Home</th> 
 
          <th>Update</th> 
 
         </tr> 
 
         </thead> 
 
         <tbody> 
 
         <tr> 
 
         <td>27006</td> 
 
         <td>Fixer</td> 
 
         <td>Sam</td> 
 
         <td>testing address</td> 
 
         <td></td> 
 
         <td>123456</td> 
 
         <td>123456</td> 
 
         </tr> 
 
       </tbody> 
 
      <tbody><tr> 
 

 
       <td>test</td> 
 
       <td>test</td> 
 
       <td>test</td> 
 
       <td>test</td> 
 
       <td>test</td> 
 
       <td>test</td> 
 
       <td>test</td> 
 
      </tr> 
 
      </tbody> 
 
      </table>

謝謝