Reputation: 3938
I am using Jquery and dataTables to display some in a table. Everything works fine but now I need to be able to update a specific row on button click. To make it clear I attach a screenshot:
I need when a user is pressing the Cancel button to update the values of this row. Right now I store the values as a data attribute in the <tr>
element.
I am able to get them but I need to find an elegant way to apply the update.
Does datatables provide some functionality for this?
EDIT
When I create the table, I use the createdRow event in order to save the values of this specific element as an data attribute.
// add data using DataTable lib
var layer_data = $("#layer_data").DataTable({
"scrollX": true,
"aaData":whole_array,
"iDisplayLength": 10, // display 10 rows on each page
// on createdRow add data-initial attribute with the data of the row
"createdRow": function ( row, data, index ) {
$.each($('td', row), function (colIndex) {
$(this).parent().attr('data-initial', data);
});
}
});
Later I use an on click event (when cancel button is clicked). I retrieve the values stored in the data attribute. I need to put these values back in the cells of the row.
// functionality to cancel edits
$(document.body).on("click", "._cancel_btn",function(e){
console.log($(this).closest('tr').attr('data-initial'));
});
Upvotes: 1
Views: 2475
Reputation: 85538
I think it is straight forward. You have stored an array of strings as initial-data
attribute on the <tr>
, these values should be populated to the row columns :
$(document.body).on("click", "._cancel_btn",function(e) {
var row = $(this).closest('tr'),
data = row.attr('data-initial').split(',')
for (var i=0; i<data.length; i++) {
table
.row(row)
.nodes()
.to$()
.find('td:nth-child('+ (i+1) +')') //css indexes is 1-based
.text(data[i])
}
})
The above works directly on dataTables internal nodes. You could do the same in "pure" jQuery and after that invalidate()
the row :
for (var i=0; i<data.length; i++) {
$('td:nth-child('+(i+1)+')', row).text(data[i])
}
layer_data.row(row).invalidate()
BTW could createdRow
be improved. You are inserting data-initial
n times (for each column) you only need
createdRow: function ( row, data, index ) {
$(row).attr('data-initial', data);
}
Upvotes: 1