edmond edmond - 3 months ago 7
jQuery Question

I cannot remove row with query

I can add dynamic rows to my invoice table when I click 'add new row' but when I have to delete the row dynamically with 'remove row' it doesn't delete.

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

$(this).parents() selects div.col-md-6 which is not what you want.

If you want to remove the last row in your table you should do:

$('#remove-row').click(function(){
    var table = $('tbody.body'); // This get the tbody element of your table

    var rowToRemove = table.find('tr').last(); // Get the last row of your table
    rowToRemove.remove();
});


But if you want to select a specific row to remove you should make a way to select rows and THEN remove them. Personnaly I would mark them as selected and then remove them like this:

$('tbody.body').on('click', 'tr', function(){ // Notice ON instead of CLICK, it is to select row that will be added  later on
    var row = $(this); // select the row that has been clicked
    row.toggleClass('selected-row'); // mark the row as selected
});

$('#remove-row').click(function(){
    var table = $('tbody.body'); // Select the table
    var rows = table.find('tr.selected-row'); // Select all the row that are marked for deletion
    rows.remove(); // then remove them all
});
Comments