I am working on jquery datatable
. I am adding user input data into rows.
$('.add-row').on('click', function() {
name = $('#name').val();
email = $('#email').val();
cno = $('#cno').val();
bdy = $('#bday').val();
t.row.add([
name,
email,
cno,
bdy,
'<button class ="btn btn-danger del">Delete</button>' + '' + '<button class="btn btn-warning upd" data-id="'+$('#example').DataTable().rows().count()+'">Edit</button>'
]).draw(false);
$("#name").val('');
$("#email").val('');
$("#cno").val('');
$("#bday").val('');
});
In the above code, there is data-id
in which I am adding rows count. Now I am also deleting the row.
$("body").on("click", ".del", function() {
if ($(row).hasClass('child')) {
t.row($(row).prev('tr')).remove().draw();
} else {
t.row($(this).parents('tr')).remove().draw();
}
});
After deleting the row. The row count is n-1
. I want to get the latest data-id
value whenever I try to add new row. For example I have added 3 rows and the row count is 3 so the data-id
would be 3. So I want to get the last/latest value of data-id
Any help would be highly appreciated?
UPDATED
i search the max data-id, so no problem of duplicate
as suggested by @FilipKováč, if you are sure the last row has always the max id, you could try: var max = parseInt($("button.upd").last().data("id") || 0);
instead of my line with map.. its better in performance
$('.add-row').on('click', function() {
var values = $.map($("button.upd"), function(el, index) { return parseInt($(el).attr("data-id")); });
var max = Math.max.apply(null, values.length == 0 ? [0] : values);
name = $('#name').val();
email = $('#email').val();
cno = $('#cno').val();
bdy = $('#bday').val();
t.row.add([
name,
email,
cno,
bdy,
'<button class ="btn btn-danger del">Delete</button>' + '' + '<button class="btn btn-warning upd" data-id="'+ (max + 1) +'">Edit</button>'
]).draw(false);
$("#name").val('');
$("#email").val('');
$("#cno").val('');
$("#bday").val('');
});
$("body").on("click", ".del", function() {
if ($(row).hasClass('child')) {
t.row($(row).prev('tr')).remove().draw();
} else {
t.row($(this).parents('tr')).remove().draw();
}
});
if you want to reindex data-id:
$("button.upd").each(function(index){
$(this).attr("data-id", index);
}
you do that in delete function.. and you keep your initial code in your Add function
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.