Unbind Doesn't Work on DataTable Search

Unbind Doesn't Work on DataTable Search

apfanzapfanz Posts: 11Questions: 3Answers: 0

We are using DataTable for thousands of records and are using server-side processing for performance reasons. The problem comes with searching. We don't want the search to hit the server after each keystroke as this degrades performance. I did some searching and did find a thread

https://datatables.net/forums/discussion/33028/searchdelay-for-server-side-issue

that discusses an ideal solution for us. Someone, pjdarch, found a way to have the search run 1 second after the user is done typing. I tried the jQuery unbind and bind method suggested in the thread, but the DataTable is ignoring it and is not working as expected. I have an example set up at

http://live.datatables.net/canakedi/3/edit

I would appreciate any ideas.

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 21,349Questions: 26Answers: 4,955

    A couple of suggestions:

    1. Use jQuery off() and .on() instead of unbind and bind.
    2. Have you looked at using searchDelay instead?

    Kevin

  • apfanzapfanz Posts: 11Questions: 3Answers: 0

    1) I tried using off() and on() at http://live.datatables.net/vebiqoxa/1/edit but it doesn't seem to make any difference
    2) I have looked at searchDelay and experimented with it but am unsure of the exact time I should use as we have users who type both slowly and quickly

  • kthorngrenkthorngren Posts: 21,349Questions: 26Answers: 4,955

    Looks like there is a timing issue with adding the Search element to the DOM and immediately trying to access it. Move the code into initComplete like this:
    http://live.datatables.net/vebiqoxa/1/edit

    Kevin

  • apfanzapfanz Posts: 11Questions: 3Answers: 0

    I could not find the initComplete function in the code at http://live.datatables.net/vebiqoxa/1/edit. Perhaps it is in another link?

  • kthorngrenkthorngren Posts: 21,349Questions: 26Answers: 4,955
    Answer ✓

    Here is the code:

    $(document).ready( function () {
      var oTable = $('#example').DataTable({
        initComplete: function () {   // initComplete
          $('.dataTables_filter input')
          .off() // Unbind previous default bindings
          .on('input', (delay(function (e) { // Bind our desired behavior
            oTable.search($(this).val()).draw();
            return;
          }, 1000))); // Set delay in milliseconds
    
        }
      });
    } );
    

    Kevin

  • apfanzapfanz Posts: 11Questions: 3Answers: 0

    Thanks Kevin. That worked!

Sign In or Register to comment.