【问题标题】:Is it possible to have a Datatables search box search one column, but use dropdowns for others?是否可以让 Datatables 搜索框搜索一列,但对其他列使用下拉列表?
【发布时间】:2014-09-04 03:03:09
【问题描述】:

我正在尝试设计一个Datatables 表以满足一组特定的条件。

  1. 会有列下拉菜单,因此如果选择了某个选项,它将仅显示与该值完全匹配的列。
  2. 会有一个搜索框,输入此框会过滤第一列

不幸的是,这似乎是 DataTables 中两个相互矛盾的要求。

这段代码,允许将搜索栏限制在第一列,

numCols = $("#myTable thead tr:first th").length
columns = [{ "searchable": true }]
for (var i=1; i < numCols; i++) {
    columns.push({ "searchable": false });
}

var table = $('#myTable').DataTable({
    "paging": false,
    "columns":columns
});

但是,当使用column.search()这个代码时:

$("#myTable thead tr:first th").each( function ( i ) {
    if ($(this).hasClass("filter")) {
        var select = $('<select name="select_column_'+i+'"><option value="">ALL</option></select>')
        .appendTo( $(this).empty() )
        .on( 'change', function () {
            table.column(i)
            .search( $(this).val(),false,false,false)
            .draw();
        } );

        table.column( i ).data().unique().sort().each( function ( d, j ) {
            select.append( '<option value="'+d.replace(/[[\]\/()]/g,'\\$&')+'">'+d+'</option>' )
        });
    }
});

现在,我知道我在表格的 columns 声明中将 searchable 设置为 false,删除它可以让下拉菜单再次工作 - 但这意味着搜索文本框会过滤 所有列,而不仅仅是第一列。

遗留文档说有一个bFilterable 选项做了类似的事情,但这不再在当前版本中。现在我完全没有想法了。

那么,有没有办法限制 Datatables 表,以便搜索框仅过滤一列,同时允许基于下拉列表过滤其他列?

PS:For the curious, here is jsFiddle that shows the problem pretty clearly.

【问题讨论】:

    标签: jquery datatables


    【解决方案1】:

    事实证明,这使用标准的 Datatables API 是不可能的,但使用 jQuery 可以扩展表来管理它。

    首先,对将要搜索的每一列保持搜索(因此排除列上的任何searching 选项。

    然后通过删除f 标志来使用DataTables.dom option 关闭过滤框。

    然后在表格本身之前创建一个自定义搜索框:

    $('<input type="text" />')
        .insertBefore('#myTable')
        .before('<label>My special search: </label>')
        .on( 'keyup change', function () {
            table
            .column( 0 )
            .search( this.value )
            .draw();
        });
    

    这会将搜索仅应用于第 0 列。但是行

    .column( 0 )
    

    可以更改为匹配任意列中的字符串,如下所示:

    .columns(0,1,2)
    

    或者可以匹配搜索字符串在 all 的给定列中的行,如下所示:

    .column([0,1,2])
    

    有很多小提琴演示这个,所以你可以看到

    查看功能差异的最佳示例字符串是an

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 2020-11-21
      • 1970-01-01
      • 2020-09-25
      • 1970-01-01
      • 2023-02-23
      相关资源
      最近更新 更多