VAAA
VAAA

Reputation: 15039

How to detect checkbox select event in a table with jQuery DataTables

I am using jQuery DataTables for a table that loads data from the server using Ajax.

enter image description here

I have added a checkbox column and I need to fire an event every time I check a checkbox.

How can I do this?

Upvotes: 6

Views: 5642

Answers (2)

Irvin Dominin
Irvin Dominin

Reputation: 30993

Since, I think, you are adding these elements dynamically in render function, you can use event delegation for the click event of the checkbox.

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

Ref: http://learn.jquery.com/events/event-delegation/

Code:

$(document).on('click', '.chkRow', function () {
    alert($(this).attr('value'));
});

I found a code for this purpose that add a checkbox on the row and on the click alert an attribute value.

Demo: https://jsfiddle.net/IrvinDominin/aqa61xdf/

Upvotes: 5

Thomas Junk
Thomas Junk

Reputation: 5676

You could use the (datatables) initComplete hook to add your events. As Irvin Dominin said, delegation is the way to go. Registering events for each and every checkbox is very expensive. Event delegation uses the fact, that events bubble up to parent elements. So you could register one listener on the uppermost element and check if the target element which emitted the element is the one, you wanted.

I prepared a JS Vanilla Fiddle, which shows the road to go.

document.querySelector("tbody").addEventListener("change", function(e){
    if(e.target.tagName==='INPUT') console.log(e.target.parentNode.parentNode.id);
})

In principle I rendered a table and put one listener on the whole tbody.

Upvotes: -1

Related Questions