Reputation: 1706
I have a table and I am deleting the table rows using the following script:
$("#ordertable tr input:checked").parents('tr').remove();
Then I am updating the table ids as follows:
function updateRowCount(){
var table = document.getElementById("ordertable");
var rowcountAfterDelete = document.getElementById("ordertable").rows.length;
for(var i=1;i<rowcountAfterDelete;i++) {
table.rows[i].id="row_"+i;
table.rows[i].cells[0].innerHTML=i+"<input type='checkbox' id='chk_" + i + "'>";
var j = i+1;
$("#ordertable tr:nth-child("+j+")").find("td").eq(1).find("select").attr("id","pn_"+i);
$("#ordertable tr:nth-child("+j+")").find("td").eq(2).find("input").attr("id","notes_"+i);
$("#ordertable tr:nth-child("+j+")").find("td").eq(3).find("input").attr("id","qty_"+i);
table.rows[i].cells[4].id = "pdctid_"+i;
}
}
I need a condition in such a way that user can not allow to delete last row.
I mean in deletion If user marked last row checkbox then I should get an alert.
Upvotes: 0
Views: 984
Reputation: 147363
It seems you want to not delete the last row with a checked checkbox. So you'd get the row to be deleted, then get the row with the last checked checkbox. If they're the same row, don't delete. Otherwise, delete.
The following is just an example of putting the above algorithm to the test. Of course there is much to improve to suit your circumstance.
E.g.
function deleteRow(el) {
// Get the row candidate for deletion
var row = el.parentNode.parentNode;
// Get last checked checkbox row, if there is one
var table = row.parentNode.parentNode;
var cbs = table.querySelectorAll('input:checked');
var cbRow = cbs.length? cbs[cbs.length - 1].parentNode.parentNode : null;
// If the row to be deleted is the same as the last checked checkbox row
// don't delete it
if (row === cbRow) {
alert("Can't touch this...");
// Otherwise, delete it
} else {
row.parentNode.removeChild(row);
}
}
<table>
<tr>
<td>0 <input type="checkbox">
<td><button onclick="deleteRow(this)">Delete row</button>
<tr>
<td>1 <input type="checkbox">
<td><button onclick="deleteRow(this)">Delete row</button>
<tr>
<td>2 <input type="checkbox">
<td><button onclick="deleteRow(this)">Delete row</button>
</table>
Upvotes: 1