jQuery DataTables:输入至少3个字符或者点击按钮后再进行搜索

92

是否有选项只在输入三个字符后开始搜索?

我为同事编写了一个显示20,000条目的PHP脚本,他们抱怨当输入单词时,前几个字母会导致一切都冻结。

另一种选择是通过点击按钮而不是键入字符来启动搜索。

以下是我的当前代码:

$("#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'
        }
} );

1
仅针对延迟,在dataTable配置中尝试以下操作 { searchDelay: value } value是以毫秒为单位的整数 - Avi
24个回答

0

你需要修改jquery.datatables.js

----- 更新 当然你可以对长度进行检查,是否大于3个字符,但我认为你仍然需要一个计时器。如果你有很多数据,在每次字符更新后不想一直进行过滤。

在这个方法内部:

jqFilter.keyup( function(e) {
            if ( **this.value**.length > 3) {
                var n = oSettings.aanFeatures.f;
                for ( var i=0, iLen=n.length ; i<iLen ; i++ )
                {
                    if ( n[i] != this.parentNode )
                    {
                        $('input', n[i]).val( this.value );
                    }
                }
                /* Now do the filter */
                _fnFilterComplete( oSettings, { 
                    "sSearch": this.value, 
                    "bRegex":  oSettings.oPreviousSearch.bRegex,
                    "bSmart":  oSettings.oPreviousSearch.bSmart 
                } );
         }
        } );

在其中一个答案中,添加一个计时器到keyup事件。

然后前往该网站 http://jscompress.com/

将您修改后的代码粘贴进去,JavaScript代码将会被压缩。


你好,谢谢 - 但我能否添加一个$('.input').length > 3或$(#input').length > 3的检查,而不是使用计时器?不过我不确定如何引用搜索字段。 - Alexander Farber
当然你可以对长度进行检查,确保大于3,但我认为你仍需要一个计时器。如果你有很多数据,你不想在每个字符更新后都重新过滤它。我已经更新了答案,正确检查长度超过3个字符。添加计时器是下一步有价值的步骤。 - Tahir Malik

0
你可以在Medtronic的数据表或其他代码中使用此代码,在使用3个字符后进行搜索:
        onDataLoad: function (RequestGrid) {
            // execute some code on ajax data load
            var searchInput = $('div.dataTables_filter input').val();
            if (searchInput.length() > 3 || searchInput.length() ==0) {
                alert(searchInput);
                dt.draw();
            }
            else {
                return false;
            }
        },

当首次显示时,searchInput.length() ==0。


0

这适用于 DataTables 版本 1.10.19。它只需要在您的网站模板中包含 js - 对于在不同页面上配置了多个 dataTables 的站点非常有用。对于任何慢速 xhr 加载表格也很有用,它将不允许任何新的 xhr 请求,直到所有当前运行的请求完成。所使用的搜索功能与插件最初设置的搜索功能非常相似。

(function(window, document, $){
var xhring = 0;

$(document).on( 'preXhr.dt', function () {
    xhring++;
} );
$(document).on( 'xhr.dt', function () {
    xhring--;
} );

//at a minimum wait the full freq, and wait for any pending XHR requests to finish before calling fn
function choke( fn, freq ) {
    var
        frequency = freq !== undefined ? freq : 200,
        last,
        timerFn,
        timer;

    return function () {
        var
            that = this,
            args = arguments;

        timerFn = function () {
            if (xhring || +new Date() < last + frequency) {
                clearTimeout( timer );
                timer = setTimeout( timerFn, frequency);
            } else {
                fn.apply( that, args );
            }
        }
        last = +new Date();

        clearTimeout( timer );
        timer = setTimeout( timerFn, frequency );
    };
}

//See https://github.com/DataTables/DataTables/blob/156faa83386460c578e00c460eca9766e38a0c5f/media/js/jquery.dataTables.js
//See https://github.com/DataTables/Plugins/blob/master/features/searchHighlight/dataTables.searchHighlight.js
$(document).on( 'preInit.dt', function (e, settings, json) {
    var previousSearch = settings.oPreviousSearch;

    var searchFn = function() {
        /* Update all other filter input elements for the new display */
        var val = !this.value ? "" : this.value; // mental IE8 fix :-(

        /* Now do the filter */                                                                                                  
        if ( val != previousSearch.sSearch && (val.length >= 3 || val == "")) {
            $.fn.dataTable.ext.internal._fnFilterComplete( settings, {
                "sSearch": val,
                "bRegex": previousSearch.bRegex,
                "bSmart": previousSearch.bSmart ,
                "bCaseInsensitive": previousSearch.bCaseInsensitive
            } );

            // Need to redraw, without resorting
            settings._iDisplayStart = 0;
            $.fn.dataTable.ext.internal._fnDraw( settings );
        }
    };

    var searchDelay = settings.searchDelay !== null ?                                                                            
        settings.searchDelay :
        $.fn.dataTable.ext.internal._fnDataSource( settings ) === 'ssp' ?
            700 :
            200;

    var jqFilter = $( 'input', settings.aanFeatures.f )
        .off('keyup.DT search.DT input.DT paste.DT cut.DT')
        .on('keyup.DT search.DT input.DT paste.DT cut.DT', choke(searchFn, searchDelay))
        ;
} );

})(window, document, jQuery);

-2

你为什么不直接在“change”事件上检查长度呢?

$('.input').change(function() {
  if( $('.input').length > 3 ) {
     //do the search
  }
});

3
由于DataTables已经绑定了这个功能并自动调用搜索功能,因此您需要拦截/修改绑定的内容。 - random_user_name

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接