Javascript 在 jQuery 数据表中初始化搜索输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11006402/
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-08-24 03:59:46  来源:igfitidea点击:

Initialize search input in jQuery Datatables

javascriptjquerydatatablesjquery-events

提问by bikedorkseattle

I'm trying to initialize a Datatable with a default search value that the user can either replace or refine on. This is with server-side data. I haven't read anything where you can do this in the Datatables documentation.

我正在尝试使用用户可以替换或优化的默认搜索值来初始化数据表。这是服务器端数据。我没有在 Datatables 文档中阅读任何可以执行此操作的内容。

$('#example_filter label input[type=text]').val('Default Product')

The above sets the value but because there isn't a keypress involved the event handler doesn't pick it up. Is there a method I can chain onto the above that would act like the enter key, or should I write an event handler that looks for changes in the field. I'm pretty new to datatables and a jQuery novice.

上面设置了值,但因为没有涉及按键,事件处理程序不会选择它。有没有一种方法可以链接到上面的方法,就像输入键一样,或者我应该编写一个事件处理程序来查找字段中的变化。我对数据表和 jQuery 新手很陌生。

回答by bikedorkseattle

So the proper way of doing this is using the oSearch parameter.

所以这样做的正确方法是使用 oSearch 参数。

https://datatables.net/docs/DataTables/1.9.0/DataTable.defaults.oSearch.html

https://datatables.net/docs/DataTables/1.9.0/DataTable.defaults.oSearch.html

$(document).ready( function() {
  $('#example').dataTable( {
    "oSearch": {"sSearch": "Initial search"}
  } );
} )

回答by gilly3

You can trigger an event manually with .trigger():

您可以使用以下命令手动触发事件.trigger()

$('#example_filter label input[type=text]')
    .val('Default Product')
    .trigger($.Event("keypress", { keyCode: 13 }));

Depending on your code, you may want "keyup"instead.

根据您的代码,您可能需要"keyup"

回答by josh123a123

The proper way is now:

现在正确的方法是:

var table = $( '#mytable' ).DataTable();
table.search( 'initial search value' ).draw();

回答by devlin carnate

The answers referring to oSearchare using legacy syntax. As of DataTables 1.10+, the correct syntax is:

所指的答案oSearch是使用旧语法。 从 DataTables 1.10+ 开始,正确的语法是:

$(document).ready( function() {
  $('#example').dataTable( {
    "search": {"search": "Initial search"}
  });
});

回答by Naoa Lee

$('#example_filter label input[type=search]').val(i).trigger($.Event("keyup", { keyCode: 13 }));

回答by Katarzyna Wi?cko

You can change default settings:

您可以更改默认设置:

var my_config = {
            oLanguage: {
                sSearch: ""
            },
            oSearch: {
                sSearch: "Default Search value"
            }
        };
$('#search').dataTable(my_config);