I am sending a request to an API and i am getting all the data and mapping it to a table and at the same time displaying a button for each row and am appending to the button an ID which is coming from the data. The problem is when i give the button an ID lets say remove and create a function to fire upon the button click nothing is happening not even registering that its been clicked and below is the code:
$(document).ready(function () {
$("#documentsDatatable").DataTable({
"processing": true,
"serverSide": true,
"filter": true,
"ajax": {
"url": 'https://localhost:44389/api/Document/Group',
"type": "POST",
"data": {id: 90},
"datatype": "json"
},
"columnDefs": [{
"targets": [0],
"visible": false,
"searchable": false
}],
"columns": [
{ "data": "name", "name": "Name", "autoWidth": true },
{ "data": "name", "name": "Document", "autoWidth": true },
{
data: "created_at",
"render": function (value) {
if (value === null) return "";
return moment(value).format('DD/MM/YYYY');
}
},
{
"render": function (data, type, full, meta) {
return "<button value='" full.id "' id='remove' class='btn btn-danger'><i class='fas fa-minus-circle'></i> Remove from Group</button>";
}
},
]
});
});
Here is the function which should fire up:
$('#remove').on('click', function (e) {
$.ajax({
type: 'POST',
url: "https://localhost:44389/api/Group/Remove",
data: {id: 4, group: 46},
dataType: 'json',
success: function (data) {
//console.log('success', data);
},
});
e.preventDefault();
});
The above code is failing to even fire up the function but when i create a random button like below and replace the ID with the one on this button the code is working perfectly. Anyone know what the problem is?
<button id="trial" value="50">Click me</button>
CodePudding user response:
Use something like this.
---------------------------------------------------------
"render": function (data, type, full, meta) {
return `<button onclick=remove( ${full.id}) class='btn btn-danger'><i class='fas fa-minus-circle'></i> Remove from Group</button>`;
}
---------------------------------------------------------
function remove (id) {
$.ajax({
type: 'POST',
url: "https://localhost:44389/api/Group/Remove",
data: { id: id, group: 46 },
dataType: 'json',
success: function (data) {
//console.log('success', data);
},
})
};
--------------------------------------------------------------