jQuery Datatables自定义搜索插件

时间:2017-01-18 19:50:24

标签: javascript jquery search filter datatables

在Web开发方面,我是初学者。我正在将我的C#winforms应用程序转换为Web应用程序。

我正在尝试使用jQuery Datatables插件在桌面上实现自定义搜索。考虑自定义搜索示例(https://datatables.net/examples/plug-ins/range_filtering.html)。我想展示所有员工的详细信息,除了他们的办公室在"爱丁堡"。

通过textbox过滤其他员工。

基本上sql相当于

select * from employees where office not like '%Edinburgh%';

这将显示所有员工及其详细信息,但办公室位于爱丁堡的员工除外。 我想对这些员工进行过滤。

修改

我使用jQuery数据表编译了一个小提琴(https://jsfiddle.net/53futc2w/5/)并填充了数据。

单击非SC按钮时,我只想显示没有" SC "的值。在他们的描述中。

基本上sql相当于

select * from products where description not like '%SC%';

根据文本框中提供的输入过滤这些值

此致

1 个答案:

答案 0 :(得分:0)

我不确定'爱丁堡'是否应该是硬编码的,或者如果您希望用户能够指定自己的值,那么这里是硬编码的解决方案,并为用户提供评论 - 提供的价值选项:

$.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {
    var exclude = 'Edinburgh'; // User provided value: $("#user-exclude-field").val();

    if(!exclude) return true; // nothing to exclude, so all rows should be included

    var re = new Regexp("\\b" + exclude + "\\b", "i"); // using the \b word boundary meta-character to match only "Edinburgh" and not "NewEdinburgh" (typo on purpose)
    return !re.test(data.office); // return TRUE (i.e. include this row in the search results) if the "office" attribute of the current row data does NOT match our excluded word
});

<强>更新

所以根据你的评论,这是一个小提琴样本:

https://jsfiddle.net/bjLzkjnc/

更新2

因此,您希望能够过滤包含单词的所有项目,或者过滤所有不包含该单词的行。更新小提琴:jsfiddle.net/1xh3kys5

这里的魔力是filter变量。之前它只是一个布尔变量,因为我们想跟踪两个状态:“包含SC”与“向我展示一切”。但现在你实际上有三种状态:“包含SC”,“向我展示一切”和“向我展示包含SC”的所有内容......所以布尔值已经不够了。

有几种方法可以解决这个问题,但我选择了过滤器对象,这样您最终可以轻松添加更多过滤器:

var filters = {
    sc: {active: false, re: new RegExp("\\bSC\\b", "i"), include: true}
};

此处的filters对象只有一个属性,一个名为“sc”的过滤器。该属性本身就是一个对象,它有一些属性可以让我们代表我们所有的三种状态:

  • 有效是打开/关闭此特定“sc”过滤器。因此,当您想要显示所有行时,只需将其设置为false,然后停用sc过滤器。
  • include 是我们的布尔值,用于控制是否要包含或排除包含单词“SC”的行。
  • 重新只是我们想要过滤行时使用的正则表达式。

当我们现在过滤行时,我们只需使用正则表达式来确定特定行是否包含“SC”。

var includes_sc = filters.sc.re.test(data[2]);
return (filters.sc.include ? includes_sc : !includes_sc);

因此,基于“include”属性的值,并将其存储在名为includes_sc的变量中。如果当前过滤器想要包含“SC”的所有行,我们将按原样返回includes_sc。另一方面,如果我们想要不包含“SC”的所有行,则返回includes_sc的反向(!includes_sc)。

希望这有帮助!