如何通过两个输入文本字段组合表格中的搜索? [英] How to combine search in table by two input text fields?

查看:40
本文介绍了如何通过两个输入文本字段组合表格中的搜索?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的桌子是这样的:

<table>
   <tr>
      <td>Apple</td>
      <td>Green</td>
   </tr>
   <tr>
      <td>Grapes</td>
      <td>Green</td>
   </tr>
   <tr>
      <td>Orange</td>
      <td>Orange</td>
   </tr>
</table>

搜索javascript如下:

The searching javascript as follows:

var $rows = $('#table tr');
$('#search').keyup(function() {
    var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();

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

看这个例子,以更好地理解我的问题:

Look at this example to understand my problem better:

http://jsfiddle.net/7BUmG/4398/

我使用第一个输入字段过滤表行.然后,当我使用第二个输入字段时,不包括第一次搜索的结果.我该如何解决?

I filter table rows with the first input field. Then, when I use the second input field, results of first search are not included. How can I fix it?

推荐答案

您当前的逻辑有些混乱.您正在重新显示和重新隐藏每个搜索字段的筛选出的项目.您真正想要的是一次性过滤所有内容,如下所示:

Your current logic is a little confused. You are re-showing and re-hiding the filtered items for every search field. What you really want is to filter it all in one go like so:

var $rows = $('#table tr');
$('#search1, #search2').on('input', function() {
    var val1 = $.trim($('#search1').val()).replace(/ +/g, ' ').toLowerCase();
    var val2 = $.trim($('#search2').val()).replace(/ +/g, ' ').toLowerCase();
    
    $rows.show().filter(function() {
        var text1 = $(this).find('td:nth-child(1)').text().replace(/\s+/g, ' ').toLowerCase();
        var text2 = $(this).find('td:nth-child(2)').text().replace(/\s+/g, ' ').toLowerCase();
        return !~text1.indexOf(val1) || !~text2.indexOf(val2);
    }).hide();
});

body {padding: 20px;}
input {margin-bottom: 5px; padding: 2px 3px; width: 98px;}
td {padding: 4px; border: 1px #CCC solid; width: 100px;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="search1" placeholder="Type to search">
<input type="text" id="search2" placeholder="Type to search">
<table id="table">
   <tr>
      <td>Apple</td>
      <td>Green</td>
   </tr>
   <tr>
      <td>Grapes</td>
      <td>Green</td>
   </tr>
   <tr>
      <td>Orange</td>
      <td>Orange</td>
   </tr>
</table>

这当然是假设列和过滤器字段的数量不是动态的.如果您要这样做,则需要检查索引,而不是对 td:nth-​​child(1) td:nth-​​child(2)

That's of course assuming non-dynamic number of columns and filter fields. If that's what you're after, you need to check the index rather than hard coding td:nth-child(1) and td:nth-child(2)

这篇关于如何通过两个输入文本字段组合表格中的搜索?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆