Remove line from datatable
I am trying to delete using jQuery a row choosing id="data(Number)"
from datatable how to do it. Is this possible, or id
would it be better on tag <tr>
instead of tag <td>
?
<table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered">
<thead>
<tr>
<th>Check</th>
<th>Field_1</th>
<th>Field_2</th>
<th>Field_3</th>
</tr>
</thead>
<tbody id="dataTable">
<tr>
<td><input type='checkbox' id='data1'><br></td>
<td>Field_1_Input1</td>
<td>Field_2_Input1</td>
<td>Field_3_Input1</td>
</tr>
<tr>
<td><input type='checkbox' id='data2'><br></td>
<td>Field_1_Input2</td>
<td>Field_2_Input2</td>
<td>Field_3_Input2</td>
</tr>
</tbody>
</table>
source to share
Try:
function removerow(number){
$('#data'+number).closest('tr').remove();
}
and then you can call, for example removerow(2)
, to remove a line with an input element withid=data2
UPDATE (from comments)
To get also the text of the elements td
in a string using $("#data"+i)
try:
$('#data' + number).parent().siblings().each(function () {
console.log($(this).text());
});
source to share
Using the API with data manipulation is easy to use and can help if you are using paging
etc. which will update the number of pages in the document after the row is removed.
// datatable intitalization.
$('#userInfo').DataTable({
'paging': true,
'lengthChange': true,
"lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
'searching': true,
'info': true,
'autoWidth': true,
'stateSave': true,
'ordering': true,
'deferRender': true,
columnDefs: [
{ targets: [4], orderable: false }
]
});
// function to remove datatable row.
function RemoveDatatableRow(rowId){
var row = $("#" + rowId);
$("#userInfo").dataTable().fnDeleteRow(row);
}
source to share
tableID = $('#dataTableInfoUser');
var table = tableID.DataTable().rows().nodes();
var rowCount = table.length;
for (var i = 0; i < rowCount; i++) {
var row = tableID.DataTable().row(i).node();
var chkbox = row.cells[0].childNodes[0];
if (null != chkbox && true == chkbox.checked) {
tableID.dataTable().fnDeleteRow(i);
rowCount--;
}
}
source to share