0

I'm adding dynamically rows to a table, I have a "remove row" button to remove current row from the table. It's working correctly except I want to leave at least on row in the table. To do that, I added a test to get the current number of rows inside the table but it always return 1, it's like the value is not updated, why not ?

Here is the table :

<table id="fla_inf" width="100%">
<tr>
<th class="tab_header" colspan="6">Flavors and Additives</th>
</tr>
<tr>
    <th class="tab_header_nam">Flavor Brand</th>
    <th class="tab_header_nam">Flavor Name</th>
    <th class="tab_header_nam">Dropper Type</th>
    <th class="tab_header_nam">Quantity</th>
    <th class="tab_header_nam">Total %</th>
    <th class="tab_header_nam">Add/Remove row</th>
</tr>
<tbody>
<tr>
     <td><select id="marque.0" name="marque,0"></select></td>
     <td><select id="arome.0" name="arome.0"></select></td>
     <td><select id="dropper.0" name="dropper.0"></select></td>
     <td><input id="quantity.0" name="quantity.0" type="number"/></td>
     <td><input id="fla_perc.0" name="fla_perc.0" type="number" min="0" max="100"/></td>
     <td><input class="addline" type="image" src="http://spitilab.com/wp-content/uploads/2015/01/add.png"><input class="remline" type="image" src="http://spitilab.com/wp-content/uploads/2015/01/delete.png"></td>
</tr>
</tbody>
</table>

and here is the remove part of the code :

// Remove row from the table
$(document).on('click', '.remline', function() {
    alert($('#fla_inf').length);
    if ($('#fla_inf').length > 1) {
        $(this).closest('tr').remove();
    }
});

2 Answers 2

2

You need to find the length of tr elements:

$('#fla_inf tr').length;

COMPLETE CODE:

$(document).on('click', '.remline', function() {
alert($('#fla_inf tr').length);
if ($('#fla_inf tr').length > 1) {
    $(this).closest('tr').remove();
}});
Sign up to request clarification or add additional context in comments.

Comments

0

If you want to always keep one row in the table body, excluding the rows in the header(you have 2 rows), you can use:

$(document).on('click', '.remline', function() { 
  alert($('#fla_inf tbody tr').length);  
  if ($('#fla_inf tbody tr').length > 1) {  
    $(this).closest('tr').remove();  
  }
});

1 Comment

Thank you, I start to understand better how to filter to specific elements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.