can anyone help me on how to get a single row data on a click event.
This is the table which is dynamically populated after Success function in AJAX call is executed
<div class="table-responsive table-wrap tableFixHead container-fluid">
<table class="table bg-violet dT-contain" id="datatable" >
<thead class="thead-dark">
<tr>
<th>No.</th>
<th>Main</th>
<th>Shrinked</th>
<th>Clicks</th>
<th>Disable</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<tr class="bg-violet">
</tr>
</tbody>
</table>
</div>
<script src="scripts/jquery-3.5.1.min.js"></script>
<script src="scripts/jquery.dataTables.min.js"></script>
<script src="scripts/dataTables.bootstrap4.min.js" defer></script>
<script src="scripts/dashboard.js" defer></script>
This is my ajax success function
success: function(data){
$('#datatable').dataTable({
data: data,
"autoWidth": true,
columns: [
{'data': 'id'},
{'data': 'main'},
{'data': 'shrinked'},
{'data': 'clicks'},
{"defaultContent": "<button id='del-btn'>Delete</button>"}
]
})
}
I am adding a delete button to each row dynamically, but can’t seem to fetch row data using it.
I tried this method with some tweaks to my success function
$('#datatable tbody').on( 'click', 'button', function () {
var data = table.row( $(this).parents('tr') ).data();
alert( data[0] );
} );
But this didn’t seem to work.
The JSON data returning from the AJAX call is in this format:
[{"id":"12","main":"ndkekfnq" ...}, {.....}]
I also added an onclick function on the delete button to try to fetch data but that also didn’t work.
EDIT: whole AJAX request
$(document).ready(()=>{
$.ajax({
url: 'URL',
method: 'post',
dataType: 'json',
data: {
"email": window.email,
"token": window.token
},
success: function(data){
let table = $('#datatable').dataTable({
data: data,
"autoWidth": true,
columns: [
{'data': 'id'},
{'data': 'main'},
{'data': 'shrinked'},
{'data': 'clicks'},
{"defaultContent": "<button id='dis-btn' class='btn btn-warning'>Disable</button>"},
{"defaultContent": "<button id='del-btn' class='btn btn-danger'>Delete</button>"}
]
})
$('#datatable tbody').on('click', "#del-btn", function() {
let row = $(this).parents('tr')[0];
//for row data
console.log(table.row(row).data().id);
});
}
})
})
What would be the correct way to do this? Thank you
3
Answers
Here is working code for you. You need to set the
datatables
in avar
.Use that
var table
to look forclicked
row
which will$(this).parents('tr')[0]
and use.data.id
to the clicked itemid
I have recreated the your example and its working fine. Just set you
ajax
response to thedata
.Demo
You need to use column.render instead o defaultContent and then get the data on an outside function, you need to render a button at the render of the table:
Haven’t tried, but based on Datatables docs, this should work, let me know if it worked.
@Javier ‘s answer is a very good way to solve the OP’s issue. Another way, if you don’t want to include id field twice, would be like this: