6

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?

1
  • How does your dataTables initialisation code looks like? Commented Oct 2, 2015 at 16:22

2 Answers 2

5

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/

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for leaving the links to my article jQuery DataTables – How to add a checkbox column. Good answer! One minor note is that I would isolate the selector to the actual table $('#example') instead of $(document) in case there are multiple tables, but it's a matter of personal preference.
Yep, better for multiple grids. Always leave the credits
-1

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.

2 Comments

addEventListener is available in IE9 only. Also your code targets all input elements instead of only <input type="checkbox">
Yes you're right. But I understand my solution as a hint, not as a "copy & paste" and everything will be good solution. Therefor I wrote »which shows the road to go«

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.