jQuery DataTables:延迟搜索直到输入 3 个字符或单击按钮

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

jQuery DataTables: Delay search until 3 characters been typed OR a button clicked

jquerydatatables

提问by Alexander Farber

Is there please an option to start the search only after 3 characters have been typed in?

是否可以选择仅在输入 3 个字符后开始搜索?

I have written a PHP-script for colleagues displaying 20,000 entries and they complain, that when typing a word, the first few letters cause everything to freeze.

我为同事编写了一个 PHP 脚本,显示了 20,000 个条目,他们抱怨说,在输入单词时,前几个字母会导致所有内容冻结。

An alternative would be to have the search to be started by a button clicked and not by character typing.

另一种方法是通过单击按钮而不是通过键入字符来开始搜索。

Below is my current code:

以下是我当前的代码:

$("#my_table").dataTable( {
        "bJQueryUI": true,
        "sPaginationType": "full_numbers",
        "bAutoWidth": false,
        "aoColumns": [
                /* qdatetime */   { "bSearchable": false },
                /* id */          null,
                /* name */        null,
                /* category */    null,
                /* appsversion */ null,
                /* osversion */   null,
                /* details */     { "bVisible": false },
                /* devinfo */     { "bVisible": false, "bSortable": false }
        ],
        "oLanguage": {
                "sProcessing":   "Wait please...",
                "sZeroRecords":  "No ids found.",
                "sInfo":         "Ids from _START_ to _END_ of _TOTAL_ total",
                "sInfoEmpty":    "Ids from 0 to 0 of 0 total",
                "sInfoFiltered": "(filtered from _MAX_ total)",
                "sInfoPostFix":  "",
                "sSearch":       "Search:",
                "sUrl":          "",
                "oPaginate": {
                        "sFirst":    "<<",
                        "sLast":     ">>",
                        "sNext":     ">",
                        "sPrevious": "<"
                },
                "sLengthMenu": 'Display <select>' +
                        '<option value="10">10</option>' +
                        '<option value="20">20</option>' +
                        '<option value="50">50</option>' +
                        '<option value="100">100</option>' +
                        '<option value="-1">all</option>' +
                        '</select> ids'
        }
} );

采纳答案by random_user_name

Solution for version 1.10 -

版本 1.10 的解决方案 -

After looking here for a complete answer and not finding one, I've written this (utilizing code from the documentation, and a few answers here).

在在这里寻找完整的答案但没有找到之后,我写了这篇文章(利用文档中的代码和这里的一些答案)。

The below code works to delay searching until at least 3 characters are entered:

以下代码用于延迟搜索,直到输入至少 3 个字符:

// Call datatables, and return the API to the variable for use in our code
// Binds datatables to all elements with a class of datatable
var dtable = $(".datatable").dataTable().api();

// Grab the datatables input box and alter how it is bound to events
$(".dataTables_filter input")
    .unbind() // Unbind previous default bindings
    .bind("input", function(e) { // Bind our desired behavior
        // If the length is 3 or more characters, or the user pressed ENTER, search
        if(this.value.length >= 3 || e.keyCode == 13) {
            // Call the API search function
            dtable.search(this.value).draw();
        }
        // Ensure we clear the search if they backspace far enough
        if(this.value == "") {
            dtable.search("").draw();
        }
        return;
    });

回答by Richard

Note: This was for a much earlier version of data tables, please see this answerfor jQuery datatables v1.10 and above.

注意:这是针对更早版本的数据表,请参阅jQuery数据表v1.10 及更高版本的此答案



This will modify the behaviour of the input box to only filter when either return has been pressed or there are at least 3 characters in the search:

这将修改输入框的行为以仅在按下返回键或搜索中至少有 3 个字符时进行过滤:

$(function(){
  var myTable=$('#myTable').dataTable();

  $('.dataTables_filter input')
    .unbind('keypress keyup')
    .bind('keypress keyup', function(e){
      if ($(this).val().length < 3 && e.keyCode != 13) return;
      myTable.fnFilter($(this).val());
    });
});

You can see it working here: http://jsbin.com/umuvu4/2. I don't know why the dataTables folks are binding to both keypress and keyup, but I'm overriding both of them to stay compatible although I think keyup is sufficient.

你可以在这里看到它的工作:http: //jsbin.com/umuvu4/2。我不知道为什么 dataTables 的人同时绑定到 keypress 和 keyup,但我覆盖它们以保持兼容,尽管我认为 keyup 就足够了。

Hope this helps!

希望这可以帮助!

回答by Sam Barnes

Why not try this extended version of Stony's answer :)

为什么不试试这个 Stony 答案的扩展版本 :)

var searchWait = 0;
var searchWaitInterval;
$('.dataTables_filter input')
.unbind('keypress keyup')
.bind('keypress keyup', function(e){
    var item = $(this);
    searchWait = 0;
    if(!searchWaitInterval) searchWaitInterval = setInterval(function(){
        if(searchWait>=3){
            clearInterval(searchWaitInterval);
            searchWaitInterval = '';
            searchTerm = $(item).val();
            oTable.fnFilter(searchTerm);
            searchWait = 0;
        }
        searchWait++;
    },200);

});

This will delay the search until the user has stopped typing.

这将延迟搜索,直到用户停止输入。

Hope it helps.

希望能帮助到你。

回答by Chad Kuehn

Here is how to handle it with the api change in version 1.10

以下是如何通过 1.10 版中的 api 更改来处理它

var searchbox = $('#promogrid_filter input');
var pgrid = $('#promogrid').DataTable();

//Remove default datatable logic tied to these events
searchbox.unbind();

searchbox.bind('input', function (e) {
   if(this.value.length >= 3) {
      pgrid.search(this.value).draw();
   }
   if(this.value == '') {
      pgrid.search('').draw();
   }
   return;
});

回答by Christian Noel

Here's a plugin-like script that extends datatables.

这是一个扩展数据表的类似插件的脚本。

jQuery.fn.dataTableExt.oApi.fnSetFilteringEnterPress = function ( oSettings ) {
    var _that = this;

    this.each( function ( i ) {
        $.fn.dataTableExt.iApiIndex = i;
        var
            $this = this, 
            oTimerId = null, 
            sPreviousSearch = null,
            anControl = $( 'input', _that.fnSettings().aanFeatures.f );

            anControl
              .unbind( 'keyup' )
              .bind( 'keyup', function(e) {

              if ( anControl.val().length > 2 && e.keyCode == 13){
                _that.fnFilter( anControl.val() );
              }
        });

        return this;
    } );
    return this;
}

usage:

用法:

$('#table').dataTable().fnSetFilteringEnterPress();

回答by Marius Butuc

To do is invoke the server call after the user has typed the mininum characters in the search box, you can follow Allan's suggestion:

要做的是在用户在搜索框中输入最小字符后调用服务器调用,您可以按照艾伦的建议进行操作

customize the fnSetFilteringDelay()plug-in API functionto add an extra condition on the string length before setting the filter, also considering a blank string input to clear the filter

自定义fnSetFilteringDelay()插件API函数,在设置过滤器前对字符串长度增加额外条件,同时考虑空字符串输入清除过滤器

So for a minimum of 3 characters, just change line #19 in the plug-into:

因此,对于至少 3 个字符,只需将插件中的第 19 行更改为:

if ((anControl.val().length == 0 || anControl.val().length >= 3) && (sPreviousSearch === null || sPreviousSearch != anControl.val())) {

回答by Zante

My version of datatables 1.10.10

我的数据表版本 1.10.10

I changed a little things and it works now. So, i'm sharing, cause it was difficulty to make it work for version 1.10.10. Thanks to cale_b, Stony and Sam Barnes. Look at the code to see what i did.

我改变了一些东西,现在它可以工作了。所以,我正在分享,因为很难使它适用于 1.10.10 版。感谢 cal_b、Stony 和 Sam Barnes。看看代码,看看我做了什么。

    var searchWait = 0;
    var searchWaitInterval;
    $('.dataTables_filter input')
    .unbind() // leave empty here
    .bind('input', function(e){ //leave input
        var item = $(this);
        searchWait = 0;
        if(!searchWaitInterval) searchWaitInterval = setInterval(function(){
            if(searchWait >= 3){
                clearInterval(searchWaitInterval);
                searchWaitInterval = '';
                searchTerm = $(item).val();
                oTable.search(searchTerm).draw(); // change to new api
                searchWait = 0;
            }
            searchWait++;
        },200);

    });

回答by Márcio Souza Júnior

This works on DataTables 1.10.4:

这适用于数据表 1.10.4:

var table = $('#example').DataTable();

$(".dataTables_filter input")
    .unbind()
    .bind('keyup change', function(e) {
        if (e.keyCode == 13 || this.value == "") {
            table
                .search(this.value)
                .draw();
        }
    });

JSFiddle

JSFiddle

回答by zion ben yacov

You can delay the ajax call to the server by this

您可以通过此延迟对服务器的 ajax 调用

var search_thread = null;
    $(".dataTables_filter input")
        .unbind()
        .bind("input", function(e) { 
            clearTimeout(search_thread);
            search_thread = setTimeout(function(){
                var dtable = $("#list_table").dataTable().api();
                var elem = $(".dataTables_filter input");
                return dtable.search($(elem).val()).draw();
            }, 300);
        });

This code will stop the ajax call if the time between to key press is less then 300 ms, in that way when you write a word, only one ajax call will run and only when you stop typing. You can 'play' with the delay param ( the 300) in order to get more or less delay

如果按键之间的时间少于 300 毫秒,此代码将停止 ajax 调用,这样当您写一个单词时,只有一个 ajax 调用会运行,并且只有在您停止输入时才会运行。您可以使用延迟参数(300)“播放”以获得更多或更少的延迟

回答by mato gallardo

for 1.10 version add this code to your javascript in the options. The initComplete overrides the search method and wait to 3 characters are written. Thanks to http://webteamalpha.com/triggering-datatables-to-search-only-on-enter-key-press/for giving me the light.

对于 1.10 版本,将此代码添加到您的 javascript 选项中。initComplete 覆盖搜索方法并等待写入 3 个字符。感谢http://webteamalpha.com/triggering-datatables-to-search-only-on-enter-key-press/给我亮光。

    var dtable= $('#example').DataTable( {
        "deferRender": true,
        "processing": true,
        "serverSide": true,


        "ajax": "get_data.php",
        "initComplete": function() {
            var $searchInput = $('div.dataTables_filter input');

            $searchInput.unbind();

            $searchInput.bind('keyup', function(e) {
                if(this.value.length > 3) {
                    dtable.search( this.value ).draw();
                }
            });
        }

    } );
} );