Jimmy Sikh Jimmy Sikh - 5 months ago 11
jQuery Question

Check if there are any more elements like parent - jQuery

I want to create a condition to check if there is iany row in the table or the row is the only one left.

So, I have:

<table>

<tr>
<td>AAAAAAA</td><td><a class="btn-row-delete">DELETE</a></td>
</tr>

<tr>
<td>BBBBBBB</td><td><a class="btn-row-delete">DELETE</a></td>
</tr>

<tr>
<td>CCCCCCC</td><td><a class="btn-row-delete">DELETE</a></td>
</tr>

</table>


and I want to be able to delete the rows until there is only one left. So, let's say I deleted everything and only the middle row BBBBBBB stayed like this:

<table>


<tr>
<td>BBBBBBB</td><td><a class="btn-row-delete">DELETE</a></td>
</tr>


</table>


and it doesn't allow me to delete it if it's only one tr left in the table. How to make such condition? My current code without the check, just for deleting looks like this:

$('form').on('click', '.btn-row-delete', function(e) {
e.preventDefault();
$(this).closest('tr').remove();
return false;
});


How to stop deleting if there is only one tr left in the table? Maybe disabling the button so it's not very complicated.

Answer

You could just check the length of the array which contains the <tr> elements.

if($('table tr').length>1)
   $(this).closest('tr').remove();