SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Enthusiast
    Join Date
    Feb 2007
    Posts
    40
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Calculate sum from user input form fields

    Hello, I am using a script to calculate the total of a column of input fields where the user enters amounts. I customized this script for my form and it works, except that if one of the fields is left blank it display "NaN" in my total instead of counting the blank field as zero and giving me a real total.

    Code:
    This is in the <head>:
    <script type="text/javascript">
    function calculate() {
    var total = 0;
    
    for (var i = 1; i < arguments.length; i++) {
    total += parseInt(arguments[i].value, 10);
    }
    
    arguments[0].value = total;
    }
    </script>
    
    This is my input fields... ( I have 13 fields in total):
    <input type="text" name="Tuition" size="15" tabindex="32">
    
    This is the calculate button and the total field:
    <input type="button" value="Calculate Column" onclick="calculate(this.form.total, this.form.Tuition, this.form.Books, this.form.Rent, this.form.Utilities, this.form.Heating, this.form.Food, this.form.Clothing, this.form.Transportation, this.form.Entertainment, this.form.Insurance, this.form.Laundry, this.form.creditCard, this.form.BankLoans);">
    
    <input type="text" name="total" size="15" tabindex="0">
    How can I fix this the best possible way?

    1) making the script count the field as zero if blank instead of displaying "NaN"
    or
    2) automaticly placing a zero in the field with the onBlur event.

    I'm in the process of learning more JavaScript and I'm not sure how to add one of the above option without interfering with the main script.

    Thanks for your advice!

    Julia

  2. #2
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
    n = parseInt(arguments[i].value, 10);
    if (isNaN(n)) {
      n = 0;
    }
    total += n;
    or this does the same:
    Code:
    total += parseInt(arguments[i].value, 10) || 0;

  3. #3
    SitePoint Enthusiast
    Join Date
    Feb 2007
    Posts
    40
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Wow, short and efficient, that's the way I like code. Thanks a lot Mike!

  4. #4
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)


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
  •