edmond edmond - 3 months ago 11
jQuery Question

I cannot remove row with jQuery

When I add dynamic rows to my invoice table by clicking the 'add new row' button, it works. However when I have to delete the row dynamically with the 'remove row' button it does not delete. Any ideas how this can be fixed?

Below is my code:

<tbody class="body">
<tr>
<td><input type="hidden" class="form-control" name="count[]" value="1"><span>1</span</td>
<td><input type="text" class="form-control" name="item[]" placeholder="item"/></td>
<td><input type="text" class="form-control" name="description[]" placeholder="description"/></td>
<td><input type="text" class="form-control quantity" name="quantity[]" placeholder="quantity"/></td>
<td><input type="text" class="form-control price" name="price[]" placeholder="price"/></td>
<td><input type="text" class="form-control item_discount" name="item_discount[]" value="0" placeholder="item discount"/></td>
<td><input type="text" class="form-control total" name="total[]" placeholder="total" readonly=""/></td>
</tr>
</tbody>

<div class="col-md-6">
<button type="button" class="btn btn-success" id="add-row"><i class="fa fa-plus"> Add new row</i></button>
<button type="button" class="btn btn-danger" id="remove-row"><i class="fa fa-minus"> Remove row</i></button>
</div>


$('#remove-row').click(function() {
$(this).parents().first().remove();
});


Please help. Thanks

Answer

If your new row gets added to the end of your table do the following

$( 'tbody tr:last-child' ).remove();

If you are removing the first row of your table you will need to do the following

$( 'tbody tr:first-child' ).remove();