Reputation: 37
I am creating a table dynamically from user input (JSFiddle link). I now want to sum up the textboxes in the table. To do this I have added a common class to all the input boxes and an id to the result textbox. However the onchange event is not firing when I enter a value in the textbox. What am I missing here?
Here is my JQuery for table generation code and textbox value sum:
$(document).ready(function () {
$('#amortTable').click(function () {
//User will input number of payments
var i = $('#numOfRows').val();
var s2 = "<table><th>Month No.</th><th>Cash Outflow</th>"
for (var j = 0; j < i; j++) {
s2 += "<tr><td>" + (j + 1) + "</td><td><input type='text' class='payment' id='payment" + (j + 1) + "' /></td></tr>";
}
s2 += "<tr><td></td><td><input type='text' id='paymentSum' readonly='readonly' style='background-color:#C0C0C0' /></td></tr></table>";
$('#amortizationTable').html(s2);
});
$('.payment').on("change", function () {
var sum = 0;
$(".payment").each(function () {
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
$('#paymentSum').val(sum);
});
});
Thanks in advance.
Upvotes: 0
Views: 1642
Reputation: 50905
You should use:
$("#amortizationTable").on("change", ".payment", function () {
// your code from above
});
Applied to your jsFiddle - http://jsfiddle.net/XeuB8/17/
Notice I literally only changed 1 line (commented) and it seems to work.
The reason for this is because you bind the change
event when the DOM is ready. But you are dynamically adding the rows (and input
elements). Therefore, the new elements won't have the event bound to them.
The code I provided solves that by attaching one event handler to the table element. When anything fires a change
event anywhere in the table, it checks to see if the element has the payment
class. If it does, it executes the handler in its context. Otherwise, the handler is not executed for that change
.
Here's the section about it in the jQuery docs for on
: http://api.jquery.com/on/#direct-and-delegated-events
Upvotes: 5
Reputation: 4328
The "change" event for '.payment' is not firing. I would suggest putting the sum logic within the click handler.
Upvotes: 0