2013-03-28 62 views
0

我使用此代碼來過濾搜索。我試圖只使用.filter類來過濾2列。問題是腳本現在要求文本在兩列中匹配才能過濾結果。我如何製作它,以便從任一列中找到結果,而不是兩者?jquery搜索過濾器

$(document).ready(function() { 
    var $rows = $('#orders tbody .filter'); 
    $('#filtersearch').keyup(function() { 
     var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase(); 

     $rows.closest('tr').show().end().filter(function() { 
      var text = $(this).text().replace(/\s+/g, ' ').toLowerCase(); 
      return !~text.indexOf(val); 
     }).closest('tr').hide(); 
    }); 
    $('#filtersearch').keyup(); 
}); 

而且隨着數據表

<table border="0" align="center" cellpadding="5" cellspacing="0" id="orders"> 
<thead> 
<tr> 
<th colspan="6"> 
      <form name"searchfilter"> 
      <input type="text" id="filtersearch" name="filtersearch" placeholder="Search by name or phone number" value="<?php echo $search; ?>"> 
      </form> 
      </th> 
</tr> 
<tr> 
<th width="15%">Date</th> 
<th width="30%">Name</th> 
<th width="30%">Phone</th> 
<th width="15%">Location</th> 
<th width="10%">Picked Up</th> 
</tr> 
</thead> 
<tbody> 
<?php 
/* 
     VIEW.PHP 
     Displays all data from 'players' table 
*/ 

     // connect to the database 
     include('connect-db.php'); 


     // get results from database 
     $result = mysql_query("SELECT * FROM orders") 
       or die(mysql_error()); 


     // loop through results of database query, displaying them in the table 
     while($row = mysql_fetch_array($result)) { 
    $src = ''; 
    switch($row['Location']) { 
      case '1': 
       $src = 'images/rear_icon.png'; 
       break; 
      case '2': 
       $src = '2.jpg'; 
       break; 
      default: 
       $src = 'default.jpg'; 

      }  // echo out the contents of each row into a table 
       echo "<tr>"; 
       echo '<td>' . $row['date'] . '</td>'; 
       echo '<td class="filter">' . $row['Name'] . '</td>'; 
       echo '<td class="filter">' . $row['Phone'] . '</td>'; 
       echo '<td><img src="'.$src.'"></td>'; 
       echo '<td><a href="delete.php?id=' . $row['id'] . '"><img src="images/icons/checkmark.png"></a></td>'; 
       echo "</tr>"; 
     } 


?> 
</tbody> 
</table> 
+0

你可以請張貼你的標記嗎?我不知道這些ID是指什麼。 –

+0

我忽略了這一點。剛添加它 – user2208768

回答

0

您可以用

$rows.closest('tr').hide().each(function(){ 
     if ($('td', this).filter(function(){ 
      var text = $(this).text().replace(/\s+/g, ' ').toLowerCase(); 
      return text.indexOf(val)!=-1; // too much wine to play with ~ things 
     }).length>0) $(this).show(); 
    }) 

更換

$rows.closest('tr').show().end().filter(function() { 
     var text = $(this).text().replace(/\s+/g, ' ').toLowerCase(); 
     return !~text.indexOf(val); 
    }).closest('tr').hide(); 

個人備註:命名$rows細胞不會使代碼更容易閱讀並修復。

+0

這很好。謝謝! – user2208768

+0

我目前在數據庫中有555-555-5555格式的電話號碼。由於這是在搜索該欄,我不得不爲每個我搜索的號碼手動輸入「 - 」。有沒有辦法讓它忽略價值「 - 」在一起? – user2208768

+0

是的,您可以簡單地從文本和val中刪除函數中的「 - 」,就像使用正則表達式修復空格一樣。 –