I have a form inside a table. In that table I have row for input fields. I have two options for remove row and add line. In add line when user will click a new row will be added and when user will click on remove row the last row will be removed. All this is working fine. But I have a problem that suppose I have clicked on remove row option and the last row will be removed and in this way all the rows are removed. Again now when I am clicking on add line it is not adding a new row. So can some one solve this? Here is the complete code for this
<!DOCTYPE HTML>
<html lang="en-IN">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<script type="text/javascript" src="jquery1.7.2.js"></script>
<body>
<style type="text/css">
table td {
border: 1px solid #666;
}
</style>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery("#add-line").click(function() {
var row = jQuery('.form-fields tbody>tr:last').clone(true);
row.find("input:text").val("");
row.insertAfter('.form-fields tbody>tr:last');
return false;
});
jQuery('#remove-row').live('click',function(event){
jQuery(this).parent().parent().remove();
});
});
</script>
<div id="form">
<table id="form-headings">
<tr>
<td width="15%">Remove Rows</td>
<td width="15%">Product</td>
<td width="16%">Description</td>
<td width="13%">Unit Cost</td>
<td width="14%">Quantity</td>
<td width="12%">Discount</td>
<td width="14%">Total</td>
</tr>
</table>
<div class="row">
<div class="form-fields">
<table>
<tr>
<td><input type="button" id="remove-row" value="Remove Row" /></td>
<td><input type="text" id="form_product" size="5px"/></td>
<td><input type="text" id="form_description" size="5px"/></td>
<td><input type="text" id="form_unit_cost" size="5px"/></td>
<td><input type="text" id="form_quantity" size="5px"/></td>
<td><input type="text" id="form_discount" size="5px"/></td>
<td><input type="text" id="form_total" size="5px"/></td>
</tr>
</table>
</div>
</div>
<input type="button" id="add-line" value="Add Line" />
</div>
</body>
</html>
That is because you do not have a tr able to clone when you delete the last row in the table.
In the code you are cloning and then appending it to the table..
UPDATED CODE
Also this part of your code is wrong
As once the last row is removed you wont find the tr>last .. It will return false.. So try avoiding it..
You can create a dummy row that holds this row structure and clone it from there..
I have created a .prototype class that holds the row.. Cloning it and inserting it..
Check FIDDLE