Tuesday, May 14, 2024
 Popular · Latest · Hot · Upcoming
50
rated 0 times [  54] [ 4]  / answers: 1 / hits: 43504  / 11 Years ago, wed, april 24, 2013, 12:00:00

I have a html table that dynamically adds and removes rows with jQuery. The number of rows is limited by jQuery counter which allows a user to add up to 4 rows. My problem is that when a user creates the 4th row they have reached the limit but when they delete a row the limit still remains in place and they can't add any more rows.



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));
}

More From » jquery

 Answers
9

Bunch of fixes,




  1. Removed extra handler for delete button

  2. change button ID to class as you should not duplicate ID. Read why you should not duplicate ID.

  3. Added logic to enable the Add row button. See Fixed fiddle.

  4. Removed var declaration inside Add Row handler to update the global var



http://jsfiddle.net/sqrrt/2/



$(table.order-list).on(click, .ibtnDel, function (event) {
$(this).closest(tr).remove();
calculateGrandTotal();

counter -= 1
$('#addrow').attr('disabled', false).prop('value', Add Row);
});

[#78648] Tuesday, April 23, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
amari

Total Points: 736
Total Questions: 111
Total Answers: 90

Location: Saint Pierre and Miquelon
Member since Fri, Jan 28, 2022
2 Years ago
;