Abhi1988 Abhi1988 - 1 month ago 20
HTML Question

Dynamically created checkbox click event selecting the whole row instead of only the check box in a jquery datatable. Why is that?

I have added a new row in my jquery datatable with html content(checkbox input) on some event as:

$("#btn").on( 'click', function (){
$('#mytable').DataTable().row.add([data[0],data[1],"<td><input type=\"checkbox\" value=\"\" /></td>"]).draw();
}


Now, when I click on the 'checkbox' from the dynamically created row, the whole row is getting triggered along with the checkbox. Hence, the below even is not getting triggered:

$('input[type=checkbox]').on( 'click', function (e){
e.stopPropagation();
});


But in turn triggers this event:

$("#mytable tbody").on( 'click', 'tr', function (){
$(this).addClass('selected').siblings().removeClass('selected');
....
}


Any idea why is this happening?

Answer

You can't stop propagation on a delegated event handler as it has already propagated through the DOM before it's handled.

Alternatively you can inspect the event.target in the tr click handler and not do any work if it was the checkbox that was clicked:

$("#mytable tbody").on('click', 'tr', function(e) {
    if (e.target.tagName.toLowerCase() == 'input')
        return;

    $(this).addClass('selected').siblings().removeClass('selected');
})
Comments