faqts : Computers : Programming : Languages : JavaScript

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

4 of 4 people (100%) answered Yes
Recently 4 of 4 people (100%) answered Yes

Entry

how do you add up the results from a for loop? (enter1,2,3,4) result = 10

Apr 7th, 2008 22:48
ha mo, Dave Clark, Jean-Bernard Valentaten, naheem hahn,


var sum = 0;
var maxNum = 4;
for (var i = 0; i <= maxNum; i++)
  sum += i;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     Note: if the values are entered as a comma-delimited list in a 
form text box, then you could use something similar to this code in a 
function:
var fld = document.forms['formName'].elements['fieldName'];
var str = fld.value;
var ary = str.split(",");
var x, cnt = 0; len = ary.length;
for (x=0; x<len; ++x)
{
    ary[x] = Number(ary[x]);
    if (isNaN) break;
    cnt += ary[x];
}
if (x<len)
{
    alert('A non-numeric value found in position '+(x+1));
    fld.select();
    fld.focus();
    return false;
}
alert('The total is '+cnt);
return true;
Take care,
Dave Clark
www.DaveClarkConsulting.com
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
http://www.businessian.com
http://www.computerstan.com
http://www.financestan.com
http://www.healthstan.com
http://www.internetstan.com
http://www.moneyenews.com
http://www.technologystan.com
http://www.zobab.com
http://www.healthinhealth.com