使用多个单选按钮过滤 table 数据

Use multiple radio buttons to filter table data

我在 table 中有一些数据:

<table>
<tr>
 <th>Month</th>
 <th>Savings</th>
 <th>Rate</th>
</tr>
<tr>
 <td>January</td>
 <td>0</td>
 <td>5%</td>
</tr>
<tr>
 <td>March</td>
 <td>0</td>
 <td>4%</td>
</tr>
</table>

我想使用具有以下逻辑的单选按钮:

  1. 全部 - 1 月 - 3 月

  2. 全部 - $100 - $200

  3. 全部 - >4% - >5%

如何使用 JavaScript 搜索 table 数据,并根据 多个 单选按钮的输出显示行,而不仅仅是一个单选按钮?

我希望理解正确,但类似于这个问题:

radio-button-filter-using-jquery-javascript

我尝试在 fiddler 中显示一个与您的需求类似的划痕:jsfiddler

$('tr').each(function() {
        ...
});

您必须实施范围控制。

IlGala html5 的答案更好

如果您使用框架或库通过绑定(如 angularjs 或 knockoutjs)处理此问题,通常会容易得多。试试看!

此致

编辑:回复您的评论

你必须在条件下工作,尽量拆分在更简单的检查中。真的,绑定会帮助你。 :)

if (price > val2 && price < val3 || ...){
    $(this).show();
} else {
    $(this).hide();
}

我会混合使用 HTML5 数据标签和 jquery。

单选按钮应该有 data-first-valuedata-second-value 以恢复范围。最糟糕的部分是检查行,因为有一些 "complex" 文本,而不仅仅是您要查找的值。但是有很多 examples 可以实现您的目标。

这是您的代码的示例。

$(document).ready(function() {
    $(".radio").click(function() {        
        // hide all table rows

        // Get the rest of checked radios
        var checkedRadios = $('.radio:checked');

        // Iterate the checked radios
        $.each(checkedRadios, function(idx, element){
            // Table rows filter:
            // 1) iterate the rows
            // 2) if the table respects the filter => show
        });
    });
});

这是获得所需结果的最简单方法之一。hide/show。

编辑:做了一个 oopsie,我过滤了应该显示的内容。代码更新如下。

我用一组单选按钮做了一个测试页面,但同样的逻辑也适用于一组新的单选按钮,其 "name" 属性是您要应用的过滤器。

在此处查看下面的代码:http://jsfiddle.net/3mdc7ppb/2/

<!DOCTYPE html>
<html><head><meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<table id="TblRates">
<tr class="headerRow">
 <th>Month</th>
 <th>Savings</th>
 <th>Rate</th>
</tr>
<tr class="dataRow">
 <td>January</td>
 <td>0</td>
 <td>5%</td>
</tr>
<tr class="dataRow">
 <td>March</td>
 <td>0</td>
 <td>4%</td>
</tr>
</table>
<input type="radio" name="Month"  value="All" checked="checked" />All<br/>
<input type="radio" name="Month"  value="January"/>January<br/>
<input type="radio" name="Month"  value="March"/>March<br/>

<script>
$("input[type=radio]").change(function(){
    var filter = this.value;
    if (filter == "All")
        $("tr.dataRow").css( "visibility", "visible" );
    else $("tr.dataRow").css( "visibility", "collapse" );
    var matchFound = false;
    $("tr.dataRow").find("td").each(function() {
      $this = $(this);
      if (!matchFound){
          if ($this.html() == filter){
            matchFound = true;
            $this.parent().css( "visibility", "visible" );
          }
      }
    });
});
</script>
</body></html>