Francisunoxx Francisunoxx - 4 months ago 7
PHP Question

How to fix given row to avoid delete using .remove function

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!!

Answer

tr represents the row and td represent the row's single cell.

You should read and explore about HTML tables

 $('#customFields tr:last').remove();

Working Demo

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();
        }

        });