javascript 带有比较运算符的 jQuery DataTables 过滤列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5223830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 16:25:52  来源:igfitidea点击:

jQuery DataTables filter column with comparison operators

javascriptjqueryjquery-pluginsfilteringdatatables

提问by DTing

I've been using the DataTables jQuery plugin with the filter plug in, and it is awesome. However, I was wondering if it is possible to filter table columns by row using a comparison operator (e.g. '<' '>' or '<>') before a value in the filter input at the bottom of the table.

我一直在使用带有过滤器插件的 DataTables jQuery 插件,它很棒。但是,我想知道是否可以在表格'<' '>' or '<>'底部的过滤器输入中的值之前使用比较运算符(例如)逐行过滤表格列。

http://www.datatables.net/plug-ins/filtering#functions

http://www.datatables.net/plug-ins/filtering#functions

There is way to filter by range using input fields that accept a max and min value. However, I'd like to forgo adding two additional input fields and somehow parse the input of this column.

有一种方法可以使用接受最大值和最小值的输入字段按范围过滤。但是,我想放弃添加两个额外的输入字段并以某种方式解析此列的输入。

The row i want to filter is populated with only integers (age) values.

我要过滤的行仅填充整数(年龄)值。

some examples of desire behaviour:

欲望行为的一些例子:

input      results
< 20       less than than 20
> 20       greater than 20
20 - 80    between 20 and 80
<> 20      not 20

Anyone have experience modifying the behavior of the filter plugin to achieve this behavior? Thanks.

任何人都有修改过滤器插件的行为以实现此行为的经验?谢谢。

edit:

编辑:

example image

示例图像

I'd like to be able to directly type in the comparison operator into these input boxes. If an operator is detected it will filter based on the operator. If no filter operator is detected, I'd like it to filter normally.

我希望能够直接在这些输入框中输入比较运算符。如果检测到操作员,它将根据操作员进行过滤。如果未检测到过滤器运算符,我希望它正常过滤。

the html for the filter input looks like this:

过滤器输入的 html 如下所示:

<tfoot>
    <tr>
        ...
        <th class=" ui-state-default">
            <input type="text" class="search_init" value="Age" name="search_age">
        </th>
        <th class=" ui-state-default">
            <input type="text" class="search_init" value="PD Status" name="search_age_of_onset">
        </th>
        ...
    </tr>
</tfoot>

Thanks!

谢谢!

回答by ttubrian

The 3 steps needed should be:

所需的 3 个步骤应该是:

  • create the UI
  • write a filtering function
  • setup events to redraw the DataTable when the UI changes
  • 创建用户界面
  • 写一个过滤函数
  • 设置事件以在 UI 更改时重绘 DataTable

First create the UI. For me, the easiest way to capture the user's intent is to use a select box where the user can pick which comparison operator he wants to use:

首先创建用户界面。对我来说,捕捉用户意图的最简单方法是使用一个选择框,用户可以在其中选择他想要使用的比较运算符:

<select id="filter_comparator">
  <option value="eq">=</option>
  <option value="gt">&gt;=</option>
  <option value="lt">&lt;=</option>
  <option value="ne">!=</option>
</select>
<input type="text" id="filter_value">

Now, you need to push a function into the set of filters. The function simply grabs the specified comparison operator and uses it to compare the row data with the value entered. It should return true if a row should stay visible and return false if it should go away based on the filter. If the user doesn't enter a valid number it returns true. Change the column_index to the appropriate value:

现在,您需要将一个函数推送到过滤器集中。该函数只是获取指定的比较运算符并使用它来比较行数据与输入的值。如果一行应该保持可见,它应该返回 true,如果它应该基于过滤器消失,则返回 false。如果用户未输入有效数字,则返回 true。将 column_index 更改为适当的值:

$.fn.dataTableExt.afnFiltering.push(
  function( oSettings, aData, iDataIndex ) {
    var column_index = 2; //3rd column
    var comparator = $('#filter_comparator').val();
    var value = $('#filter_value').val();

    if (value.length > 0 && !isNaN(parseInt(value, 10))) {

      value = parseInt(value, 10);
      var row_data = parseInt(aData[column_index], 10);

      switch (comparator) {
        case 'eq':
          return row_data == value ? true : false;
          break;
        case 'gt':
          return row_data >= value ? true : false;
          break;
        case 'lt':
          return row_data <= value ? true : false;
          break;
        case 'ne':
          return row_data != value ? true : false;
          break;
      }

    }

    return true;
  }
);

Finally, at the point where you create your DataTable, setup events on your UI elements to redraw the table when the user makes changes:

最后,在创建 DataTable 时,在 UI 元素上设置事件以在用户进行更改时重绘表格:

$(document).ready(function() {
    var oTable = $('#example').dataTable();
    /* Add event listeners to the filtering inputs */
    $('#filter_comparator').change( function() { oTable.fnDraw(); } );
    $('#filter_value').keyup( function() { oTable.fnDraw(); } );
});


ON THE OTHER HAND, if you would like the user to type the comparison operator instead of selecting it then you will need to parse their input. If you have a simple text box:

另一方面,如果您希望用户输入比较运算符而不是选择它,那么您将需要解析他们的输入。如果您有一个简单的文本框:

<input type="text" id="filter">

Then you can parse the input in a filter function like this:

然后你可以像这样在过滤器函数中解析输入:

$.fn.dataTableExt.afnFiltering.push(
    function( oSettings, aData, iDataIndex ) {
        var filter = $('#filter').val().replace(/\s*/g, '');
        var row_data = aData[3] == "-" ? 0 : aData[3]*1;

        if (filter.match(/^<\d+$/)) {
            var num = filter.match(/\d+/);
            return row_data < num ? true : false;
        }
        else if (filter.match(/^>\d+$/)) {
            var num = filter.match(/\d+/);
            return row_data > num ? true : false;
        }
        else if (filter.match(/^<>\d+$/)) {
            var num = filter.match(/\d+/);
            return row_data != num ? true : false;
        }
        else if (filter.match(/^\d+$/)) {
            var num = filter.match(/\d+/);
            return row_data == num ? true : false;
        }
        else if (filter.match(/^\d+-\d+$/)) {
            var num1 = filter.match(/^\d+/);
            var num2 = filter.match(/\d+$/);
            return (row_data >= num1 && row_data <= num2) ? true : false;
        }
        return true;
    }
);

and a document ready:

并准备好文件:

$(document).ready(function() {
    var oTable = $('#example').dataTable();
    /* Add event listeners to the filtering inputs */
    $('#filter').keyup( function() { oTable.fnDraw(); } );
});

This filter only works on positive integers. Decimals and negative number support would require more work. You could also extend the function to add >= and <= support, or just make those the default behavior for > and < depending on your user expectations.

此过滤器仅适用于正整数。小数和负数支持需要更多的工作。您还可以扩展该函数以添加 >= 和 <= 支持,或者根据您的用户期望将这些设置为 > 和 < 的默认行为。

I've also once again attached the event listener to a free floating input text box. I've tried this with a basic DataTable and it works. You would need to attach the behavior to those text boxes at the bottom of your columns, but I'm not sure how you got them there - I've never done that with a DataTable.

我还再次将事件侦听器附加到一个自由浮动的输入文本框。我已经用一个基本的 DataTable 尝试过这个并且它有效。您需要将行为附加到列底部的那些文本框,但我不确定您是如何将它们放在那里的 - 我从来没有用 DataTable 这样做过。