Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind change event to checkbox in each DataTables row

I have added a checkbox for each row in DataTables. When table data is loaded, I bind change event to each checkbox like this:

fnInitComplete: function(oSettings, json) {

      $("input[type='checkbox']").on("change", function() {

            // checking if any checkbox is checked

      });
}

The problem is that change event is added only for the first page. If I navigate to other pages and click on any checkbox, no event is fired. It works only if I refresh the page. Same is with Show entries. What would be a clever way to deal with this issue?

Table data

like image 764
Mr. Blond Avatar asked Aug 11 '16 14:08

Mr. Blond


2 Answers

Try using delegated events:

$("#table_id").on('change',"input[type='checkbox']",function(e){
    //your code 
});

This tells the table to run the specified function when a 'change' event originated from an input[type='checkbox'] that is its descendant.

You don't need to register this handler in the table initialization by the way, you can just do it after the document is ready.

More about delegated events

like image 182
Sebastianb Avatar answered Nov 15 '22 05:11

Sebastianb


You can place your code here .on( 'page.dt', function () { // do something}) check the link for more explanation about this or you could place this event around with below code.

$(function(){$("input[type='checkbox']").on("change", function() {

            // checking if any checkbox is checked

      });})
like image 38
Nalin Aggarwal Avatar answered Nov 15 '22 07:11

Nalin Aggarwal