I current have a table that is sorted by DataTables with bootstrap integration. In my final column i have a button group (edit, complete etc) that should call functions when clicked.
The buttons are created using this code in a php while loop, with data-id being the variable that the javascript needs to receive
echo "<button type=\"button\" class=\"complete btn btn-default btn-xs\" data-id=\"" . $row["id"] . "\"><span class=\"glyphicon glyphicon-ok\"></span></button>";
Javascript:
$(".complete").click(function() {
var id = $(this).data("id");
alert(id);
})
This works on page load but the minute i sort the table, the functions stop working with no output to console! Any help on why this isn't working?
EDIT:
Sort function
/* Datatables */
$("#tasks").dataTable({
"aoColumns": [
null,
null,
{"sType": "date-uk"},
{"bSortable": false}
]
});
$.extend($.fn.dataTableExt.oSort, {
"date-uk-pre": function (a) {
var ukDatea = a.split("/");
return (ukDatea[2] + ukDatea[1] + ukDatea[0]) * 1;
},
"date-uk-asc": function (a, b) {
return ((a < b) ? -1 : ((a > b) ? 1 : 0));
},
"date-uk-desc": function (a, b) {
return ((a < b) ? 1 : ((a > b) ? -1 : 0));
}
});
/* End */
Buttons should be recreated on sort as data is not loaded through ajax
You should delegate event to table level:
$("#tasks").on("click",".complete",function() {
var id = $(this).data("id");
alert(id);
})