2013-03-28 351 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中删除函数中的“ - ”,就像使用正则表达式修复空格一样。 –