You're multiplying the sum of all prices by the sum of all attendees. You want to do the multiplication per row:
function paymentTicketChanges() {
var total = 0;
$('.ticketing-row').each(function(index, el) {
var me = $(this);
// Convert to number early, note the +
var attendees = +me.find('.payment_number_attendees').val();
var price = +me.find('.payment_ticket_price').val();
if ((attendees >= 1) && (price >= 1)) {
// Do the sum here, add to total
total += attendees * price;
}
});
// Use total
$('.payment_ticket_total span').text(total);
$('.card-payment #amount').val(total);
}
Perhaps use .toFixed(2)
on total
at the end.
Live Example:
$("input").on("input", paymentTicketChanges);
paymentTicketChanges();
function paymentTicketChanges() {
var total = 0;
$('.ticketing-row').each(function(index, el) {
var me = $(this);
// Convert to number early, note the +
var attendees = +me.find('.payment_number_attendees').val();
var price = +me.find('.payment_ticket_price').val();
if ((attendees >= 1) && (price >= 1)) {
// Do the sum here, add to total
total += attendees * price;
}
});
// Use total
$('.payment_ticket_total span').text(total.toFixed(2));
$('.card-payment #amount').val(total.toFixed(2));
}
<table>
<tbody>
<tr>
<th>Attendees</th>
<th>Price</th>
</tr>
<tr class="ticketing-row">
<td><input class="payment_number_attendees" value="2"></td>
<td><input type="text" class="payment_ticket_price" value="29.99"></td>
</tr>
<tr class="ticketing-row">
<td><input type="text" class="payment_number_attendees" value="3"></td>
<td><input class="payment_ticket_price" value="10.00"></td>
</tr>
</tbody>
</table>
<div class="payment_ticket_total">Total: <span></span></div>
<div class="card-payment">Amount: <input type="text" id="amount"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Side note: Beware JavaScript numbers and financial amounts (see: Is floating point math broken?).
Side note 2: There are lots of ways to convert to number from string. All of the built-in ones have some kind of downside (parseInt
and parseFloat
stop on the first invalid character instead of failing, Number
and +
treat ""
as though it were 0). Here's where I've ended up on it, FWIW:
function toNumber(str) {
str = str.trim();
return str === "" ? NaN : +str;
}
Side note 3: They're harmless, but the inner ()
in your if
are completely unnecessary. :-)