91

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

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.

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'
        }
} );
Alexander Farber
  • 21,519
  • 75
  • 241
  • 416
  • 1
    For delay only try this in dataTable config { searchDelay: value } value is an integer of milliseconds – Avi Dec 25 '21 at 07:43

24 Answers24

94

Solution for version 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:

// 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;
    });
random_user_name
  • 25,694
  • 7
  • 76
  • 115
  • 4
    For those of you having trouble getting this to work, try using this in the `init.dt` event, e.g. `$('#yourTable').on('init.dt', function () { ... });`. – arao6 Nov 25 '14 at 00:22
  • In version 11, you need to set first the search string and then to run the fnDraw() as follows: $(".datatable").dataTable().api().search("aaaa2");$(".datatable").dataTable().fnDraw() – Hesham Yassin Dec 15 '14 at 13:23
  • @HeshamYassin - that's what this does, but note that this code references the returned instance object (`dtable` in the code above) to redraw, rather than setting up a new instance. – random_user_name Dec 15 '14 at 16:34
  • looks like e.keyCode is undefined, at least on my end, also I am also trying to get what is this type of event "input" – talsibony Sep 09 '15 at 07:15
  • @talsibony - if e.keyCode is undefined, it's because (likely) the "e" is missing in the function parameters. Pay close attention to this part: `.bind("input", function(e) {` <- that "e" in there is critical. – random_user_name Sep 09 '15 at 14:09
  • e.keyCode == 13 does't seem to work. When i enter one character and press enter nothing happens – azza idz Oct 21 '15 at 14:13
  • 3
    I had input instead of keydown function, it's working nicely now. Thank you – azza idz Oct 22 '15 at 11:15
  • Useful bit of code - I found I had to alter the Jquery selector to $("#[datatable_name]_filter input") to get it to bind correctly – Liam Sep 22 '16 at 12:14
  • I am using v1.10.12, and it gives error like this "table.api is not a function", When I removed ".api()" part it worked for me. – Alisettar Huseynli Oct 13 '16 at 07:50
  • That was a typo... I fixed it. – Maxime Dec 07 '16 at 14:20
  • @cale_b My edit was wrong as it was incomplete. That said, you set `dtable` that is not used and use `table` that is not defined. – Maxime Dec 07 '16 at 14:46
  • No problem! We are here to provide the best answer! Please go ahead... it's your answer. Note that you will need to remove the `.api()` where `dtable` will be called. :-) – Maxime Dec 07 '16 at 15:32
  • 1
    @Maxime I've rolled it back to the edit that worked and didn't make those erroneous variable name mismatches. Let me know if you think it still needs edits / attention. – random_user_name Dec 07 '16 at 15:33
  • @cale_b - Awesome answer, thank you - it worked "out of the box" as your answer is typed except one issue. I had to change the bind parameter from `"input"` to `"keyup"` in order to get the function to register the enter key (yes, I had the `function(e)`). Prior to, it was not picking up that value at all. Version 1.10.12, jQuery 3.1.1 – Tommy Jan 26 '17 at 15:35
  • `var dtable = $(".datatable").DataTable();` – madzohan Nov 10 '17 at 08:42
  • @cale_b I mean `var dtable = $(".datatable").dataTable().api();` didn't work for me :) but this one`var dtable = $(".datatable").DataTable();` did work – madzohan Nov 13 '17 at 11:38
  • 2
    @cale_b I can confirm this is still working for 1.10.16. Thank you. – AnotherDeveloper Nov 15 '17 at 17:26
  • I had to bind to "keyup" to get the keyCode and "input" to get the clear click. .bind("keyup input") – AnthonyVO May 15 '19 at 22:18
  • 3
    Is there a better solution for this in 2020? :) – Hackeron May 01 '20 at 21:34
  • I had to update following to make it work. i have removed .api() on datatable and changed $(".dataTables_filter input") to $("#NAME_OF_DATATABLE_filter input") to find the proper input by selector. I have added following code to make sure user get the results refreshed when backspace is used in search box. else if (this.value.length <= 3 && e.keyCode == 8) { table.search(this.value).draw(); – user1551655 Feb 17 '21 at 01:11
  • Can't believe it's 2022 and there's still no built-in solution for this – Leticia Esperon Jan 04 '22 at 16:47
77

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


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:

$(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.

Hope this helps!

Community
  • 1
  • 1
Richard
  • 4,740
  • 4
  • 32
  • 39
  • 2
    Noticed this as well. Binding to both keypress and keyup means the query is fired twice. For those watching at home, you should just take out one or the other from both the unbind and bind. – Thunder Rabbit Feb 09 '12 at 07:26
  • 1
    this solution doesn't work when pressing the backspace. @Sam Barnes is the best answer – Idrees Khan Apr 24 '13 at 10:14
  • 2
    As an alternative to Sam Barnes' excellent answer, you can amend this to account for backspacing (and clearing the field) by replacing `e.keycode != 13` with `e.keyCode > 13`, which will also fire when they tab out of the field. – cincodenada May 30 '13 at 00:11
  • 2
    Unfortunately this does **not work** with version 1.10 – random_user_name May 27 '14 at 19:52
  • Following what @ThunderRabbit said, the best way I found was to unbind both, but only re-bind one or the other. `.unbind('keypress keyup') .bind('keypress', function(e) ...` – nageeb May 05 '15 at 19:36
  • This solution not not working because you have also catch input event, so .unbind('keypress keyup input') ... – zalex Dec 21 '16 at 11:20
  • if you dont use fnInitComplete in DataTables legacy version for this resolution, it just bind a new keypress and keyup event but it doesnt remove (off) dataTables default keypress and keyup event. – cihancoskun Jul 26 '19 at 08:22
33

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

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.

Sam Barnes
  • 331
  • 3
  • 2
  • works nice. but I have to change oTable.fnFilter(...) to refer to my data table instance. – YudhiWidyatama Feb 09 '13 at 14:55
  • This isn't really an extended version, it's a totally different (but useful) solution. I am confused, though, as to what the searchWait parameter does that couldn't be accomplished by `setTimeout(function(){...}, 600)`, since the function doesn't seem to get re-fired on further characters. – cincodenada May 30 '13 at 00:50
  • @cincodenada it has to be a `setInterval`, because it refires every 200/600ms and checks if searchWait was not reset to 0. e.g. if you continue to enter something to the input, you will always reset searchWait to 0 = search is never executed. However, I find the use of searchWait as integer, which counts to 3, rather obscure. Better would be just a true/false-flag if user input happened and a `setInterval` of 600. – r3mark Jun 10 '13 at 07:03
  • 3
    Since jqueryDatatables 1.10.3, there is an option for this: [searchDelay](https://datatables.net/reference/option/searchDelay) – panmari Aug 31 '15 at 08:55
  • 2
    @panmari - searchDelay will just delay the searching for the specified time and will (trigger ajax) redraw the table afterwards, not when the user stopped typing which most of us expecting. – Chris Landeza Mar 10 '16 at 04:33
13

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

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;
});
2Yootz
  • 3,971
  • 1
  • 36
  • 31
8

To 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 function to add an extra condition on the string length before setting the filter, also considering a blank string input to clear the filter

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

if ((anControl.val().length == 0 || anControl.val().length >= 3) && (sPreviousSearch === null || sPreviousSearch != anControl.val())) {
Marius Butuc
  • 17,781
  • 22
  • 77
  • 111
  • 2
    THIS is the right solution to latest 1.11.x. It combines the search delay hack with the min chars required to trigger the search. All other solutions only partially worked. Thank you a lot!! – Luciano Fantuzzi Sep 04 '21 at 22:34
8

This works on 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

Litisqe Kumar
  • 2,512
  • 4
  • 26
  • 40
Marcio J
  • 673
  • 7
  • 17
8

My version of datatables 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.

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

    });
Zante
  • 81
  • 1
  • 2
7

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();
Christian Noel
  • 305
  • 4
  • 14
  • Don't you want "if length is more than 2 *or* enter key pressed? `if ( anControl.val().length > 2 || e.keyCode == 13)` – Jeromy French May 01 '13 at 03:43
  • yup, that also works. i'm just more focused on the validation-side so that even if an empty string is passed and the enter key was pressed nothing happens. – Christian Noel May 03 '13 at 06:40
5

None of the previous solutions worked for me so I have made this modified version that also adds a debounce. Working perfectly with all the latest versions.

You can simply change or remove the min character limit and debounce timeout value.

jQuery(document).on( 'init.dt', function (e, settings) {
  var dti = jQuery('.dataTables_filter input');
  var api = new jQuery.fn.dataTable.Api( settings );
  var dbn = null;

  dti.off().on('input', function(e) {
    clearTimeout( dbn );
    var str = this.value;
    dbn = setTimeout(function(){
      if(str.length > 2 || e.keyCode == 13) api.search( str ).draw();
      if(str == '') api.search( '' ).draw();
    }, 300);
    return;
  });
});
Jomac
  • 495
  • 5
  • 10
3

Use this

   "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
            });
        }
Nitin Bourai
  • 430
  • 7
  • 20
  • +1 Nice. This integrates nicely in the datatables definition. btw in my case it was sufficient not to return the whole aoData obj, but only aoData[5]['value']['value'] (the text typed in the input field). – Werner Jul 06 '17 at 14:45
3

although it does not answer the original question, i had a complex and slow search on my datatables. the filter event was firing after each keypress, which meant a quite noticeable delay after 10 characters. so by introducing a short delay after a keypress before the filter event was fired, where a subsequent keypress reset the counter and prevented the previous search, i was able to make the search seem much faster. others may find this helpful.

i used the answers from stony and christian noel to make this:

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;
}
pgee70
  • 3,707
  • 4
  • 35
  • 41
3

You can delay the ajax call to the server by this

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

zion ben yacov
  • 715
  • 6
  • 13
3

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.

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

    } );
} );
mato gallardo
  • 96
  • 2
  • 2
2

You can get the length of the data that is being passed in using data.currentTarget.value.length, please see below.

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

and obviously you would want this code to run when removing text so set the value to 0

Tom McDonough
  • 1,176
  • 15
  • 18
2

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();
        }
    });
Tino
  • 21
  • 1
2

You'll probably have to modify the plugin.

And instead of making it X characters, use a delay, so the search starts once they stopped typing for 1 second or so.

So the keydown/keyup binding which is currently triggering the search would be modified with a timer...

var timer;
clearTimeout(timer);
timer = setTimeout(searchFunctionName, 1000 /* timeToWaitInMS */);
smdrager
  • 7,327
  • 6
  • 39
  • 49
2

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());
                    });
                }
cihancoskun
  • 591
  • 5
  • 7
1

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
Starscream1984
  • 3,072
  • 1
  • 19
  • 27
Lokesh S
  • 426
  • 4
  • 13
1

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.

Chris
  • 882
  • 1
  • 10
  • 22
1

Most of the answers here in some way manipulate the existing DataTable event bindings but personally after spending far too long trying to get this working the best approach I found, in the end, was to just send a dummy value in the search parameter during the ajax call.

// ... denotes expected code for DataTable to function excluded for clarity.
$("#example").dataTable({
  ...
  'ajax': {
    ...
    'data': function (d) {
       d.search.value = d.search.value.length >= 3 ? d.search.value : "##EmptySearch##";
       return JSON.stringify(d);
    }
  }
});

The ##EmptySearch## string simply acts as a value that shouldn't match any returned data (it's entirely personal preference what to use, but it should be a string that is guaranteed to not match any data). Because the bindings have not been manipulated all the usual bells and whistles still work but nothing meaningful is returned until the search is greater than or equal to three characters. Admittedly it isn't ideal, would prefer to not make the server request at all but this is (in my opinion) the simplest approach that doesn't ruin the existing functionality of the DataTable search.

user692942
  • 16,398
  • 7
  • 76
  • 175
0

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.

Tahir Malik
  • 6,623
  • 15
  • 22
  • Hello, thanks - but could I add a $('.input').length > 3 or $(#input').length > 3 check instead of a timer? I'm not sure how to reference the search field though. – Alexander Farber Apr 13 '11 at 12:11
  • 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. **I've updated the answer with the right check on lenght above 3 characters.** Adding the timer is the next valuable step. – Tahir Malik Apr 13 '11 at 13:35
0

You can use this code on Medtronic datatable or other code to search after using 3 character :

        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 for first show.

LPLN
  • 475
  • 1
  • 6
  • 20
0

This works with DataTables version 1.10.19. It only requires including the js in your website template - useful for a site that has multiple dataTables configured on different pages. Also useful for any slow xhr loading tables, will not allow any new xhr requests until all currently running finish. The search function used is very similar to how the plugin sets up the search function originally.

(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);
site
  • 1,608
  • 14
  • 11
-2

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

$('.input').change(function() {
  if( $('.input').length > 3 ) {
     //do the search
  }
});
jimyshock
  • 115
  • 1
  • 1
  • 6