Max Segal Max Segal - 1 year ago 101
Javascript Question

Add a listener to datatables cell

I want to add a checkbox and a listener to every cell in 7th column of a table (I use datatables):

$(document).ready(function() {
// add checkbox to scheduled
$("#pm_table td:nth-child(7)").each(function() {
var site_id =2;
// $(this).closest("tr");
// add checkbox
$(this).prepend('<input type="checkbox" '+(($(this).text())!='0'?'checked':' ')
// add listener
' onchange = alert("site_id:" ' + site_id + '") '


the problem is when I try to check/uncheck the checkbox, I encounter this error:

(index):1 Uncaught SyntaxError: missing ) after argument list

what am I doing wrong, also is there a better way to add a listener to a cell using datatables?

Answer Source

The problem is due to the lack of quotes around your onchange event attribute, however you should really avoid using them at all and use a delegated event handler. Try this:

$("#pm_table td:nth-child(7)").each(function() {
    var $checkbox = $('<input type="checkbox" class="foo" />').appendTo(this);
    $checkbox.prop('checked', parseInt($(this).text(), 10) != 0);

$('#pm_table').on('change', '.foo', function() {
    var site_id = 2;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download