… and the following jQuery to calculate the input values total:
var total = 0;
$('#test').submit(function(e){
e.preventDefault();
$('.amount').each(function(index){
total += $(this).val();
});
alert(total);
});
The problem is that,upon submit, I do not get a calculated total of all values. Instead, it just echo’s out all the individual values.
What am I doing wrong here?
The problem is that JavaScript sees the values (300 and 100) as strings (text) instead of numbers. You should parse the value to a number when adding it to “total”.
You can choose between “parseInt” and “parseFloat”. parseInt is used for integers and parseFloat for decimal numbers
var total = 0;
$('#test').submit(function(e){
e.preventDefault();
$('.amount').each(function(index){
total += parseInt($(this).val());
});
alert(total);
});