Binding a click event to tr elements in jQuery Datatable on() doesn't work
I think you need live event:
$('body').on('click', '#nutzer tbody tr', function () {
aufklappen(this);
});
or can use delegate()
$('body').delegate('#nutzer tbody tr', 'click', function () {
aufklappen(this);
});
DKSan
Updated on June 14, 2022Comments
-
DKSan almost 2 years
I am developing a table that will contain all our users which can also be changed by clicking the tablerow and editing the data in a form that will open once the click was performed.
If i have all the users loaded at page load, my code works fine.
Once i change my datatable to load the users at datatable initialisation it will only work on the first page.
If i uncomment the lower part of my
ready(function())
and deletefnInitComplete
it wont even work on the first page.Here is the relevant part of my code:
$(document).ready(function(){ tbl = $('#nutzer').dataTable( { "bJQueryUI": true, "sScrollX": "100%", "bProcessing": true, "bServerSide": true, "iDisplayLength": 10, "sAjaxSource": "xhr.php", "sPaginationType": "full_numbers", "fnInitComplete": function() { $('#nutzer tbody tr').on("click", function () { aufklappen(this); } ); } } ); $( "#create-user" ).button().click(function() { $( "#dialog-form" ).dialog( "open" ); }); // $('#nutzer tbody tr').on("click", function () { // aufklappen(this); // } ); }); function aufklappen(row) { if ( tbl.fnIsOpen(row) ) { tbl.fnClose(row); } else { set = tbl.fnSettings().aoOpenRows[0]; (set != null) ? (tbl.fnClose(set.nParent)) : null; $.post("benutzerBearbeiten.php", { funktion : "benutzerDaten", id : $(row).children( "td:first-child" ).text() }, function(data){ tbl.fnOpen( row, data); $( "#deaktivieren").button().click(function(e){ e.preventDefault(); deaktivieren(); }); $( "#speichern").button().click(function(e){ e.preventDefault(); speichern(); }); } ) }; }
After page load or page change through the datatables pagination i can manualy call
$('#nutzer tbody tr').on('click', function () { aufklappen(this); } );
and the click function gets bound to the tr's perfectly.
Seems to me that the elements created by datatables-plugin are not getting up the dom to the on() handler that i defined but i cant figure out why.
EDIT
Utilising "The System Restart"s answer i ended up deleting the
fnInitComplete
part and add"asStripeClasses": [ "odd nutzer_tr", "even nutzer_tr"]
to the initialisation part and
$("body").delegate(".nutzer_tr", "click", function () { aufklappen(this); });
to the
ready(function())
. The additional classnutzer_tr
is to prevent the opened tablerow from closing.