SitePoint Sponsor

User Tag List

Results 1 to 4 of 4

Hybrid View

  1. #1
    Dinah-Moe Humm mudshark's Avatar
    Join Date
    Dec 2003
    Posts
    1,072
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Calculating total from multiple input values on submit

    I have a form similar to this:

    Code HTML4Strict:
    <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:

    Code JavaScript:
    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?

  2. #2
    SitePoint Enthusiast
    Join Date
    Oct 2012
    Posts
    41
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    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
    Code JavaScript:
    var total = 0;
    $('#test').submit(function(e){
        e.preventDefault();
        $('.amount').each(function(index){
            total += parseInt($(this).val());
        });
        alert(total);
    });

    Any issues? Shoot!

  3. #3
    Dinah-Moe Humm mudshark's Avatar
    Join Date
    Dec 2003
    Posts
    1,072
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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!

    Cheers mate!

  4. #4
    SitePoint Enthusiast
    Join Date
    Oct 2012
    Posts
    41
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    You're welcome :-)

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


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •