Not detecting clicking on a row....
Not detecting clicking on a row....
Hi all.
Am quite new to this so don't tear me to pieces please. I have the DataTables plugin displaying correctly.
My HTML is generated by this PHP code:
echo "<div>\n";
echo "<table id=\"sec0051table\" class=\"stripe cell-border hover\">";
echo "<thead>";
echo "<tr>";
echo "<th>Supplier Ref.</th>";
echo "<th>Supplier Name</th>";
echo "<th>Supplier Type</th>";
echo "<th>Address</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
if(isset($sec0051Orgs)) {
foreach ($sec0051Orgs as $sec0051Org) {
echo "<tr>";
echo "<td>" . $sec0051Org['OrganisationReference'] . "</td>";
echo "<td>" . $sec0051Org['SupplierOrgName'] . "</td>";
preg_match('#\((.*?)\)#', $sec0051Org['RelationshipDescription'], $match);
$RelDesc = $match[1];
echo "<td>" . $RelDesc . "</td>";
if($_SESSION['UserAuthenticationLevel'] >= 25) {
echo "<td>" . $sec0051Org['LongAddress'] . "</td>";
} else {
echo "<td>" . $sec0051Org['ShortAddress'] . "</td>";
}
echo "</tr>";
}
}
echo "</tbody>";
echo "</table>";
echo "</div>\n";
I am using the following JavaScript:
var table = null;
$( document ).ready( function() {
display_table();
$('#sec0051table').on('click', 'tr', function () {
var data = table.row( this ).data();
alert( 'You clicked on '+data[0]+'\'s row' );
} );
});
function display_table() {
$.ajax({
type: 'POST',
url: "./includes/modules/sec0051v101/sec0051table.php",
data: {},
success:function(data) {
$('#sec0051-2').html(data);
table = $('#sec0051table').DataTable({
select: {
style: 'single'
}
});
}
});
}
But try no matter what I do, other than the plugin saying "1 row selected" I cannot get it to detect an event when I click on a row at all.
Unfortunately at the moment the code isn't running on a publically viewable server.
Any help would be gratefully received!
Chris
This question has an accepted answers - jump to answer
Answers
In general it looks like it should work. But I suspect the ajax request is still being processed when the event handler is invoked on line 6 thus the
#sec0051table
table does not exist yet.Maybe you can try creating the handler in the ajax success function. Maybe place it after the DT init code.
Kevin
Hi Chris,
The problem here is that the Ajax call is asynchronous - so the table wouldn't have loaded by the time it gets to adding the event.
There's a few solutions for this:
$('body').on('click', '#sec0051table tr', function () {}
. This will get trigger regardless of when the data is loaded.async
/await
will sort it out, but you'll have to rely upon having modern browsersHope that helps!
Cheers,
Colin
Thank you for the help guys.
This code works!
Thanks again!