IT TIP

jQuery DataTables : 3 개의 문자를 입력하거나 버튼을 클릭 할 때까지 검색 지연

itqueen 2020. 10. 22. 23:51
반응형

jQuery DataTables : 3 개의 문자를 입력하거나 버튼을 클릭 할 때까지 검색 지연


3자를 입력 한 후에 만 ​​검색을 시작할 수있는 옵션이 있습니까?

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.10 솔루션-

여기에서 완전한 답변을 찾고 찾지 못한 후 이것을 작성했습니다 (문서의 코드와 여기에 몇 가지 답변을 활용).

아래 코드는 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;
    });

참고 : 이것은 훨씬 이전 버전의 데이터 테이블 용이었습니다. jQuery datatables v1.10 이상에 대한 답변참조하십시오 .


이것은 리턴을 눌렀거나 검색에 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());
    });
});

http://jsbin.com/umuvu4/2에서 작동하는 것을 볼 수 있습니다 . dataTables 사람들이 keypress와 keyup 모두에 바인딩하는 이유를 모르겠지만 keyup으로 충분하다고 생각하지만 호환성을 유지하기 위해 둘 다 재정의하고 있습니다.

도움이 되었기를 바랍니다!


이 확장 버전의 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);

});

사용자가 입력을 중지 할 때까지 검색이 지연됩니다.

도움이 되었기를 바랍니다.


버전 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;
});

다음은 데이터 테이블을 확장하는 플러그인과 유사한 스크립트입니다.

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;
}

용법:

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

사용자가 검색 상자에 최소 문자를 입력 한 후 서버 호출을 호출하면 Allan의 제안을 따를 수 있습니다 .

fnSetFilteringDelay () 플러그인 API 함수사용자 정의하여 필터를 설정하기 전에 문자열 길이에 대한 추가 조건을 추가하고 필터를 지우는 데 빈 문자열 입력도 고려합니다.

따라서 최소 3 자의 경우 플러그인의 19 번 줄을 다음과 같이 변경 하십시오 .

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

내 버전의 datatables 1.10.10

나는 약간의 것을 바꾸었고 지금은 작동합니다. 그래서 나는 공유하고 있는데, 버전 1.10.10에서 작동하도록 만드는 것이 어려웠 기 때문입니다. cale_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);

    });

이것은 DataTables 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


이것을 사용하십시오

   "fnServerData": function (sSource, aoData, fnCallback, oSettings) {

            if ($("#myDataTable_filter input").val() !== "" && $("#myDataTable_filter input").val().length < 3)
                return;
            oSettings.jqXHR = $.ajax({
                "dataType": 'json',
                "timeout":12000,
                "type": "POST",
                "url": sSource,
                "data": aoData,
                "success": fnCallback
            });
        }

원래 질문에 대한 대답은 아니지만 데이터 테이블에서 복잡하고 느린 검색이있었습니다. 필터 이벤트는 각 키를 누를 때마다 발생했으며, 이는 10 자 후에 상당히 눈에 띄는 지연을 의미했습니다. 따라서 필터 이벤트가 발생하기 전에 키를 누른 후 짧은 지연을 도입하여 후속 키를 누르면 카운터가 재설정되고 이전 검색이 차단되어 검색 속도가 훨씬 빨라졌습니다. 다른 사람들은 이것이 도움이 될 수 있습니다.

나는 이것을 만들기 위해 스토니와 기독교 노엘의 답변을 사용했습니다.

var dataTableFilterTimeout;
var dataTableFilterWait = 200; // number of milliseconds to wait before firing filter

$.fn.dataTableExt.oApi.fnSetFilteringEnterPress = function ( oSettings ) {
    var _that = this;
    this.each( function ( i ) {
        $.fn.dataTableExt.iApiIndex = i;
        var $this = this;
        var oTimerId = null;
        var sPreviousSearch = null;
        anControl = $( 'input', _that.fnSettings().aanFeatures.f );
        anControl.unbind( 'keyup' ).bind( 'keyup', function(e) {
            window.clearTimeout(dataTableFilterTimeout);
            if ( anControl.val().length > 2 || e.keyCode == 13){
                dataTableFilterTimeout = setTimeout(function(){
                    _that.fnFilter( anControl.val() );
                },dataTableFilterWait);
            }
        });
        return this;
    } );
    return 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);
        });

이 코드는 키 누르기 사이의 시간이 300ms 미만이면 ajax 호출을 중지합니다. 이렇게하면 단어를 쓸 때 하나의 ajax 호출 만 실행되고 입력을 중지 할 때만 실행됩니다. 더 많거나 적은 지연을 얻기 위해 지연 매개 변수 (300)로 '재생'할 수 있습니다.


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();
                }
            });
        }

    } );
} );

플러그인을 수정해야 할 것입니다.

X 문자로 만드는 대신 지연을 사용하여 1 초 정도 입력을 중지하면 검색이 시작됩니다.

따라서 현재 검색을 트리거하는 keydown / keyup 바인딩은 타이머로 수정됩니다.

var timer;
clearTimeout(timer);
timer = setTimeout(searchFunctionName, 1000 /* timeToWaitInMS */);

data.currentTarget.value.length를 사용하여 전달되는 데이터의 길이를 얻을 수 있습니다. 아래를 참조하십시오.

$('[id$="Search"]').keyup(function (data) {
            if (data.currentTarget.value.length > 2 || data.currentTarget.value.length == 0) {
                if (timoutOut) { clearTimeout(timoutOut); }
                timoutOut = setTimeout(function () {
                    var value = $('[id$="Search"]').val();
                    $('#jstree').jstree(true).search(value);
                }, 250);
            }
        });

분명히 텍스트를 제거 할 때이 코드가 실행되기를 원하므로 값을 0으로 설정하십시오.


Fixed version for datatables 1.10.12 using API and correctly unbinding the 'input'. Also added search clear on backspace under the character limit.

    // Create the Datatable
    var pTable = $('#pTable').DataTable();

    // Get the Datatable input box and alter events
    $('.dataTables_filter input')
    .unbind('keypress keyup input')
    .bind('keypress keyup input', function (e) {
        if ($(this).val().length > 2) {
            pTable.search(this.value).draw();
        } else if (($(this).val().length == 2) && (e.keyCode == 8)) {
            pTable.search('').draw();
        }
    });

If you're using the old version, it looks like it. Richard's solution works fine. But when I use it, I just added new events, not deleting. Because when code run, table is not yet created. So I found that there is the fnInitComplete method (fire when table created) and I applied it to Ricard's solution. Here it is

$("#my_table").dataTable( {
        "bJQueryUI": true,
        "sPaginationType": "full_numbers",
        "bAutoWidth": false,
         ...
         ...,
         "fnInitComplete": function (oSettings, json) {
                    var activeDataTable = $(this).DataTable();
                    $("#my_table_filter input")
                        .unbind('keypress keyup')
                        .bind('keypress keyup', function (e) {

                        if ($(this).val().length < 3 || e.keyCode !== 13) return;
                        activeDataTable.fnFilter($(this).val());
                    });
                }

Can you write your own function to test for the length of the inputed string attached to an onKeyUp event handler and trigger the search function once the min length has been reached?

Something along the lines of:

input.onKeyUp(function() {
    if(input.length > 3) {
        mySearchfunction();
    }
});

...that is, in a pseudo code kind of way but you get the jist.


You can use the parameter by name minlength in order to restrict the search until 3 characters:

function(request, response) {
    $.getJSON("/speakers/autocomplete", {  
        q: $('#keywordSearch').val()
    }, response);
}, minLength: 3

Is there a reason you wouldn't just check length on 'change'?

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

You need to modify the jquery.datatables.js

----- updated ofcourse you can do a check on lenght > 3, but I think you still need a timer. if you have a lot of data, you don't want to keep getting it filtered after every character update.

Within this method:

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 
                } );
         }
        } );

Add a timer to the keyup, like shown in one of the answers.

Then go to this site http://jscompress.com/

And past your modified code and the js wil get minified.

참고URL : https://stackoverflow.com/questions/5548893/jquery-datatables-delay-search-until-3-characters-been-typed-or-a-button-clicke

반응형