I created a table where in can add and remove dynamically. I just have a little problem where it comes to deleting a row. I want my first row to be fixed because when I used remove()
it deletes the row that I given.
Table:
<div class = "col-md-12">
<table class = "table" id = "customFields">
<thead>
<tr>
<th>Stock No.</th>
<th>Unit</th>
<th>Description</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" class="form-control"></td>
<td><input type="text" class="form-control"></td>
<td><input type="text" class="form-control"></td>
<td><input type="text" class="form-control"></td>
</tr>
</tbody>
</table>
<button type = "submit" class = "btn btn-primary" id = "addMore">+ Add</button>
<button type = "submit" class = "btn btn-danger" id = "removeRow">- Remove</button>
</div>
Script:
<script>
$(document).ready(function ()
{
$("#addMore").click(function ()
{
$("#customFields").append('<tr><td><input type="text" class="form-control"></td><td><input type="text" class="form-control"></td><td><input type="text" class="form-control"></td><td><input type="text" class="form-control"></td></tr>');
});
$("#removeRow").click(function()
{
$('#customFields td:last').remove();
});
});
</script>
I used last
function to delete the row but this only delete one textfield. How can I delete this by 4? Any help would appreciated!!
tr
represents the row and td
represent the row's single cell.
You should read and explore about HTML tables
$('#customFields tr:last').remove();
and to keep first row always , Count the tr length , and do the delete operation
$("#removeRow").click(function()
{ if($('#customFields tbody tr').length== 1){
// only one row left
alert("Cant delete first row")
}else
{
$('#customFields tr:last').remove();
}
});
And Since your thead
has a tr
too . So delete using this selection
$('#customFields tbody tr:last').remove();
it will delete tr
from tbody
only
you should select last row, instead of last table data(td). I mean in $('#customFields td:last').remove();
statement, instead of using td:last , please use tr:last.
i fixed it in this fiddle