javascript - 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
}
}
});
解决方案
这个问题有很多解决方案,但我会提到两个最简单的。
对于 HTML 来源的数据,使用单元格
data-search
属性来指定非格式化数字。例如:
<td data-search="123456">123,456</td>
有关演示和更多信息,请参阅HTML5
data-*
属性 - 单元格数据示例。对于 JavaScript 和 Ajax 来源的数据,您可以使用
columns.render
选项执行相同的操作。jQuery DataTables 使用术语正交数据,这意味着它可以将不同的数据用于不同的目的。
然后,您的数据需要包含两个附加属性,
display
用于在表格中显示和search
用于搜索。{ "data": [ { "formatted_number": { "display": "123,456", "filter": "123456" }, "office": "Edinburgh" } ] }
要使用此格式的数据,请使用以下选项作为
columns
或columnDefs
列描述:{ data: 'formatted_number', render: { _: 'display', filter: 'filter' } }
有关演示和更多信息,请参见正交数据示例。
推荐阅读
- html - 如何使用 CSS 更改文本?
- node.js - 如何为不同的客户部署同一个 node.js express API 的多个实例
- java - 每次创建新客户对象时创建唯一的客户 ID。这可能吗?爪哇
- node.js - 如何检查来自池的连接是否空闲(不忙)以供使用?(带有mariadb的nodejs)
- git - 推送新的本地标签时出现 GitPython 问题
- sonarqube - 将 SonarQube 与 Bitbucket 存储库连接起来
- codeigniter-3 - 为什么 isset 在 CodeIgniter 中取消表单验证?
- android - 条件下的 SQLite 问题
- c# - 在 Unity 中为纹理上的点创建调色板
- r - 如何仅复制 R 中列的第二个位置的信息以及多个信息