Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    Sep 2005
    Posts
    25
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Return sum of all input values within loop

    OK, so I have a bunch of input fields, each which will have a numerical value. There can be any number of input fields in the form, and that number will vary depending on what the user has selected prior in the application.

    So basically I created a loop that goes though all of the INPUT fields within the form. How can I have it find the value of each field and add them all together, then return to me the total? It'll need to be made into a variable, but a simple alert with the total value will give me enough to work with.

    Any ideas?

  • #2
    Senior Coder A1ien51's Avatar
    Join Date
    Jun 2002
    Location
    Between DC and Baltimore In a Cave
    Posts
    2,717
    Thanks
    1
    Thanked 94 Times in 88 Posts
    Basic idea:

    Code:
    var aForm = document.formName;
    for(var i=0;i<aForm.elements.length;i++){
      if(aForm.elements[i].type=="text")alert(aForm.elements[i].value);
    }
    Eric
    Tech Author [Ajax In Action, JavaScript: Visual Blueprint]

  • #3
    Senior Coder
    Join Date
    Mar 2005
    Location
    Portsmouth UK
    Posts
    4,501
    Thanks
    3
    Thanked 500 Times in 487 Posts
    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
    
    <html>
    
    <head>
      <title></title>
    <script language="JavaScript" type="text/javascript">
    <!--
    var TotalValue;
    function Total(obj,cls){
     TotalValue=0;
     var els=obj.elements;
     for (var zxc0=0;zxc0<els.length;zxc0++){
      if (els[zxc0].className==cls){
       els[zxc0].value=els[zxc0].value.replace(/\D/g,'');
       if (els[zxc0].value.length>0){
        TotalValue+=parseInt(els[zxc0].value);
       }
      }
     }
     document.getElementById('Result').value=TotalValue;
    }
    //-->
    </script></head>
    
    <body>
    <form  onkeyup="Total(this,'total');">
    <input class="total" >
    <input class="total" >
    <input class="total" >
    <input class="total" >
    <input class="total" >
    <input class="total" >
    <input id="Result" onkeyup="return false;" value="0">
    </form>
    </body>
    
    </html>


  •  

    Posting Permissions

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