Calculating total from multiple input values on submit

I have a form similar to this:

<form id="test">
    <input type="text" class="amount" value="300">
    <input type="text" class="amount" value="100">
   <input type="submit" name="submit" value="Show Total">
</form>

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

Any issues? Shoot!

Hey, thanks Denk!

That was so easy I feel stoopid now - although this guy over at StackOverflow could’ve added the bit about parseInt and parseFloat! :slight_smile:

Cheers mate!

You’re welcome :slight_smile:

We all make mistakes. I’ve edited the guy’s reponse, just waiting for confirmation.