我有一個html表格,動態地添加和刪除jQuery的行。行數受jQuery計數器限制,允許用戶添加最多4行。我的問題是,當用戶創建第四行時,他們已經達到了限制,但是當他們刪除一行時,限制仍然存在,他們不能添加更多的行。jquery添加和刪除表格行
http://jsfiddle.net/nallad1985/sqrrt/
HTML
<table id="myTable" class="order-list">
<thead>
<tr>
<td>Name</td>
<td>Price</td>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="text" name="name" />
</td>
<td>
<input type="text" name="price1" />
</td>
<td><a class="deleteRow"></a>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5" style="text-align: left;">
<input type="button" id="addrow" value="Add Row" />
</td>
</tr>
<tr>
<td colspan="">Grand Total: $<span id="grandtotal"></span>
</td>
</tr>
</tfoot>
JQUERY
$(document).ready(function() {
var counter = 0;
$("#addrow").on("click", function() {
var counter = $('#myTable tr').length - 2;
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="text" name="name' + counter + '"/></td>';
cols += '<td><input type="text" name="price' + counter + '"/></td>';
cols += '<td><input type="button" id="ibtnDel" value="Delete"></td>';
newRow.append(cols);
if (counter == 4) $('#addrow').attr('disabled', true).prop('value', "You've reached the limit");
$("table.order-list").append(newRow);
counter++;
});
$("table.order-list").on("change", 'input[name^="price"]', function (event) {
calculateRow($(this).closest("tr"));
calculateGrandTotal();
});
$("table.order-list").on("click", "#ibtnDel", function (event) {
$(this).closest("tr").remove();
calculateGrandTotal();
});
});
function calculateRow(row) {
var price = +row.find('input[name^="price"]').val();
}
function calculateGrandTotal() {
var grandTotal = 0;
$("table.order-list").find('input[name^="price"]').each(function() {
grandTotal += +$(this).val();
});
$("#grandtotal").text(grandTotal.toFixed(2));
}
感謝您的額外細節和幫助。 – nallad1985 2013-04-24 19:23:12