首页 > 解决方案 > dataTables 从格式化数字中搜索数字

问题描述

我正在使用 dataTables 在我的 HTML 表中搜索数据。

当我尝试按数字过滤时出现问题。数字已格式化,因此不会按应有的方式过滤。

一个例子:

在表格中,我有一个包含“123,456”(而不是“123456”)的单元格。

如果我在搜索框中输入“1234”,它将过滤掉这个数字。如果我输入“3,456”,它会找到我要找的东西。

我已经尝试格式化输入的数字,但效果不够好(它将'1234'格式化为'1,234',所以它不会找到'123,456',因为逗号放错了位置。另一个例子 - 如果我'会寻找'50',它会过滤掉5,000):

$( "#activity_table_filter input" ).keydown( function(){
        var current_value = $( "#activity_table_filter input" ).val();
        current_value = current_value.replace(/,/g, ''); //remove any commas from current value.
        var key = event.keyCode;
        var entered_value = String.fromCharCode( (96 <= key && key <= 105) ? key - 48 : key ); //charCode doesnt really get numpad numbers

        if( !isNaN( current_value ) && current_value != '' && !isNaN( entered_value ) ){ //if current and entered value are numeric, and current value is not an empty string
            if( current_value % 1 === 0 && current_value.length >= 3 ){ //if the number is an integer and has 3 digits
                current_value = current_value + '0'; //add a last char
                var formatted_value = parseInt(current_value).toLocaleString(); //format to beautiful
                formatted_value = formatted_value.toString(); //Convert to string
                formatted_value = formatted_value.slice(0,-1); //remove added '0' from the end
                $( "#activity_table_filter input" ).val( formatted_value ); //change value of input to formatted input.
            }else{ //if the number is a float

            }
        }
});

标签: javascriptjqueryhtmlfilterdatatables

解决方案


这个问题有很多解决方案,但我会提到两个最简单的。

  1. 对于 HTML 来源的数据,使用单元格data-search属性来指定非格式化数字。

    例如:

    <td data-search="123456">123,456</td>
    

    有关演示和更多信息,请参阅HTML5data-*属性 - 单元格数据示例。

  2. 对于 JavaScript 和 Ajax 来源的数据,您可以使用columns.render选项执行相同的操作。

    jQuery DataTables 使用术语正交数据,这意味着它可以将不同的数据用于不同的目的。

    然后,您的数据需要包含两个附加属性,display用于在表格中显示和search用于搜索。

    {
        "data": [
            {
                "formatted_number": {
                    "display": "123,456",
                    "filter": "123456"
                },
                "office":     "Edinburgh"
            }
        ]    
    }
    

    要使用此格式的数据,请使用以下选项作为columnscolumnDefs列描述:

    {
        data: 'formatted_number',
        render: {
            _: 'display',
            filter: 'filter'
        }
    }
    

    有关演示和更多信息,请参见正交数据示例。


推荐阅读