Saswat
Saswat

Reputation: 12836

Keyup functions not working on Datatable search

I have a fiddle for reference.

I am trying to have keypress events work on the search textbox of the Database. Issue is, it's not working. I can't track what's wrong?

The following code snippet seems not to be working.

if ($("#example_filter input").length > 0) {
    alert("search exists");
}
$("#example_filter input").on("keyup", function() {
    alert("hi");
});

Upvotes: 0

Views: 3663

Answers (3)

rrk
rrk

Reputation: 15846

Updated Fiddle.

The input was created after the delegation was done. The following can be used for binding a function to element which was not on DOM on ready.

$(document).on("keyup", "#example_filter input", function () {
    alert("hi");
});

Upvotes: 0

Guruprasad J Rao
Guruprasad J Rao

Reputation: 29683

The problem is you are creating your dataTable after assigning the event. So create table and then assign it!!

DEMO

$(document).ready(function()
{   
    if($("#example_filter input").length > 0)
    {
        alert("search exists");
    }

    $("#example").DataTable();
    $("#example_filter input").on("keyup",function(){
       alert("hi");    
    });
});

If you would have followed your way like creating dataTable later then you should have used event delegation as below:

DEMO

$(document).ready(function()
{   
    if($("#example_filter input").length > 0)
    {
        alert("search exists");
    }
    $(document).on("keyup",'#example_filter input',function(){
       alert("hi");    
    }); //event delegation
    $("#example").DataTable();
});

Upvotes: 0

Tushar
Tushar

Reputation: 87203

You need to first add DataTable and then bind the events. Because at the time when you bind the keyup event on input, the input was not present in the DOM.

$(document).ready(function() {
    if ($("#example_filter input").length > 0) {
        alert("search exists");
    }
    $("#example").DataTable();

    $("#example_filter").on("keyup", 'input', function() {
        alert("hi");
    });
});

Demo

Upvotes: 2

Related Questions