M.Gooda M.Gooda - 2 years ago 89
Javascript Question

How to not allow deleting all rows in table?

I have a simple table with 3 columns with classes = "code","description","delete" the column has class "delete" is a checkbox type, and one button with class="savebtn".

I need the following :

When user click save :

  1. the Jquery must verify the code column that it has data.

  2. If any cell in delete column is checked, Delete that row.

  3. If the user checked all cells in delete column alert message that the table must has at least one row , and don't delete the rows.

this is a Demo but it not working with me.

that what i tried :

$(document).ready(function (){
$(".savebtn").bind("click", function(e){
$('.table tbody tr').each(function () {
$(this).find('.code input').each(function () {
if ($(this).closest("tr").find(".delete input").is(":checked") && $('.cf-table-block tbody tr').length >=1){
$('.delete input :checkbox:checked').closest('tr').remove();
}else if($(this).closest("tr").find(".delete input").is(":checked") && $('.cf-table-block tbody tr').length <2){
}else if($('.delete input').prop('checked')==false && ( $(this).val().length>0)){
}else if ($('.delete input').prop('checked')==false && ( $(this).val().length==0)){
$(this).attr("placeholder", "Please fill this field");

Answer Source

First, you should look at wrapping your table header in <thead> and body in <tbody>. This will allow you to determine how many rows are relevant to our needs.

It'd be good to then create an array of rows that are checked to be deleted, this can then be compared (via length) to the original amount of rows.

Here's an example - I've removed a lot of the logic as the use of an array to store checked rows will help remove the need for a lot of those conditionals.

Here's a fiddle.

Edit: Here's a new fiddle in which i've added a button for you to clear/populate the last rows value so you can test.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download