/    Sign up×
Community /Pin to ProfileBookmark

Simple math question

How do you go about totaling text fields on a form. I’m working on an expense report. I have dollar values (complete with decimal points) that the users enter into text fields and I have one “total” text field at the bottom of the form that I want to dynamically be updated with the total of all the other fields, if that is possible. Otherwise, I could just have them click a button to total the box. I need some script that will do this. Is there any out there already? (I’m sure there is, I’ve seen it!) Thanks in advance.

to post a comment
JavaScript

25 Comments(s)

Copy linkTweet thisAlerts:
@guikApr 16.2003 — do you have any code, it would help to deal with your specific field
Copy linkTweet thisAlerts:
@timster69authorApr 16.2003 — None really, starting from scratch. I just about 12 text fields:

<input type="text" name="amount1" size="6" maxlength="8" value="">

<input type="text" name="amount2" size="6" maxlength="8" value="">

etc. in a form, and the final text field:

<input type="text" name="totalamount" size="6" maxlength="8" value="">

that I want to be the sum of all my other text boxes.
Copy linkTweet thisAlerts:
@guikApr 16.2003 — got some code for you. i added a javascript function(sum()).

you fill all the text area and then when you click on the last one(total amount) it displays the sum?

<html>

<head>

<script language="javascript">

<!--

function sum()

{

i = parseInt(document.Satisfait.amount1.value);

j = parseInt(document.Satisfait.amount2.value);

document.Satisfait.totalamount.value=i+j;

}

</script>

</head>

<body onload="somme()">

<form NAME="Satisfait">

<input type="text" name="amount1" size="6" maxlength="8" value="">

<input type="text" name="amount2" size="6" maxlength="8" value="">

<input type="text" name="totalamount" size="6" maxlength="8" value="" onfocus=sum()>

</form>

</body>

</html>

is that good for you?
Copy linkTweet thisAlerts:
@guikApr 16.2003 — there was a little mistake in my last code

the following works better:

<html>

<head>

<script language="javascript">

<!--

function sum()

{

i = parseInt(document.Satisfait.amount1.value);

j = parseInt(document.Satisfait.amount2.value);

(document.Satisfait.totalamount.value) = parseInt(i+j);

}

</script>

</head>

<body >

<form NAME="Satisfait">

<input type="text" name="amount1" size="6" maxlength="8" value="">

<input type="text" name="amount2" size="6" maxlength="8" value="">

<input type="text" name="totalamount" size="6" maxlength="8" value="" onfocus=sum()>

</form>

</body>

</html>

tell me is that enough
Copy linkTweet thisAlerts:
@timster69authorApr 16.2003 — That will work just fine, except, why the onload=somme()? Should that be onload=sum()?
Copy linkTweet thisAlerts:
@guikApr 16.2003 — look at the last code, it works much better.

forget "onload..." ;-)
Copy linkTweet thisAlerts:
@timster69authorApr 16.2003 — I see. I still get an "Object Expected" error when you get to the last box. And a syntax error when loading the page!
Copy linkTweet thisAlerts:
@guikApr 16.2003 — it would be easier for me to look at your code cause it works very well on my computer

so send me something guy
Copy linkTweet thisAlerts:
@guikApr 16.2003 — "object required" error is often due to the fact that you call a function without the right syntaxe. so check whether you write upper case letter instead of lower case letter . in fact check all your calls...
Copy linkTweet thisAlerts:
@timster69authorApr 16.2003 — Here's what I have:

<head>

<SCRIPT LANGUAGE="JavaScript">

<!-- Begin

function currencyFormat(fld, milSep, decSep, e) {

var sep = 0;

var key = '';

var i = j = 0;

var len = len2 = 0;

var strCheck = '0123456789';

var aux = aux2 = '';

var whichCode = (window.Event) ? e.which : e.keyCode;

if (whichCode == 13) return true; // Enter

key = String.fromCharCode(whichCode); // Get key value from key code

if (strCheck.indexOf(key) == -1) return false; // Not a valid key

len = fld.value.length;

for(i = 0; i < len; i++)

if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;

aux = '';

for(; i < len; i++)

if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);

aux += key;

len = aux.length;

if (len == 0) fld.value = '';

if (len == 1) fld.value = '0'+ decSep + '0' + aux;

if (len == 2) fld.value = '0'+ decSep + aux;

if (len > 2) {

aux2 = '';

for (j = 0, i = len - 3; i >= 0; i--) {

if (j == 3) {

aux2 += milSep;

j = 0;

}

aux2 += aux.charAt(i);

j++;

}

fld.value = '';

len2 = aux2.length;

for (i = len2 - 1; i >= 0; i--)

fld.value += aux2.charAt(i);

fld.value += decSep + aux.substr(len - 2, len);

}

return false;

}

// End -->

</script>

<-- HERE'S YOUR SCRIPT -->

<script language="javascript">

<!--

function sum()

{

i = parseInt(document.expenseform.amount1.value);

j = parseInt(document.expenseform.amount2.value);

(document.expenseform.totalamount.value) = parseInt(i+j);

}

</script>

</head>

<body>

<form action="expenseaction.asp" method="post" name="expenseform">

<b>$</b> <input type="text" name="amount1" size="6" maxlength="8" value="" onKeyPress="return(currencyFormat(this,',','.',event))">

<b>$</b> <input type="text" name="amount2" size="6" maxlength="8" value="" onKeyPress="return(currencyFormat(this,',','.',event))">

<b>$</b> <input type="text" name="totalamount" size="6" maxlength="8" value="" onfocus=sum()>

</form>


The first script just formats the values with decimal points.
Copy linkTweet thisAlerts:
@guikApr 16.2003 — i looked at your code, it works pretty well. May you give me values for which it does not work?

another probleme is that you deal with float while i used parseInt. but that's quite easy to correct

moreover you should add code to clear the field when you click in it(if the guy want to change the value).

so, what's wrong? i don't have any error with that code!
Copy linkTweet thisAlerts:
@DrDaMourApr 16.2003 — the problem was he was using ints when they are really floats. the function sum should look like



function sum()

{

(document.expenseform.totalamount.value) = parseFloat(document.expenseform.amount1.value) + parseFloat(document.expenseform.amount2.value);

}

</script>


but since you have that other script, i would put this at the end of that script, that way any time a value is changed the last box is automatically totalled
Copy linkTweet thisAlerts:
@timster69authorApr 16.2003 — Now I'm cooking with grease! Thanks a bunch guys.
Copy linkTweet thisAlerts:
@timster69authorApr 17.2003 — Just one more thing on this. I got the totals working, and everything else is working great. The only problem I'm having now is that the numbers are not rounding up with only 2 decimal places. I understand there is a "fixit" command to use, but shouldn't the "parseFloat" be doing that? My numbers are going a maximum of 15 decimal places!

Thanks again for your help.
Copy linkTweet thisAlerts:
@DrDaMourApr 17.2003 — the biggest hack of all

var x = 145.4554

x = x * 100 //x = 14545.54

x = Math.round(x); //x=14545

x = parseFloat(x);

x = x/10;

x = 145.45


i think that will work, and what happened to the way you input stuff on your form, that was what was limiting the total to two decimals.
Copy linkTweet thisAlerts:
@timster69authorApr 17.2003 — That was only limiting the decimal places in the boxes that get added up. It didn't work on the box that does the totaling. Probably cause the boxes that get added up look like this:

<input type="text" name="misc1" size="6" maxlength="8" value="0.00" onKeyPress="return(currencyFormat(this,',','.',event))">

Where the boxes that do the totaling look like this:

<input type="text" name="totalamount" size="6" maxlength="8" value="" onfocus=sum()>

Can you have an "onfocus" and a "onKeyPress" for the same box?
Copy linkTweet thisAlerts:
@DrDaMourApr 17.2003 — you wouldn't want to, but what i'm saying is, that box was adding up all the other floats, if all the other floats were only 2 decimal places then it also shoudl be 2 decimal places. Anyways, just use the above code right before you're assigning the value of the totals box (of course chaning x to whatever your total variable is)
Copy linkTweet thisAlerts:
@timster69authorApr 17.2003 — I'm taking the results of the form and sending it through an .asp page. Would it be easier to let the .asp page reformat the final number? (of course, I have to figure out how to do that too)

Where exactly am I putting this code to round off the total number?
Copy linkTweet thisAlerts:
@DrDaMourApr 17.2003 — jeeze, see above.....
Copy linkTweet thisAlerts:
@NedalsApr 17.2003 — Here's a commented script that may give you some new ideas. It does all the formatting but you can run into rounding errors. There is a workaround but needs a little more coding.

To add more fields, just drop them in and they will also be summed into the total.

<html><head><title>Untitled</title>

<script type="text/javascript">

<!--

function calc() {

var frm = document.report;

var len = frm.length - 1

var total = 0;

for (i=0; i<len; i++) {

currval = frm.elements[i].value; // currval is a STRING not a number

//frm.elements[i].value = currval.toFixed(2); // formats to 2 decimal places (curreval must be a string)

frm.elements[i].value = format(currval,2); // for IE5 and earlier

total += (currval - 0); // -0 converts currval to a number

}

//frm.elements[len] = (total+"").toFixed(2); // +"" converts total to a string

frm.elements[len].value = format((total+""),2); // +"" converts total to a string

}



// needed for IE5 and earlier. Doesn't support the toFixed() method

function format(val,n) { // Rounds and formats 'val' to 'd' decimal places (returns 0.00 on negative numbers.)

if ((!/^d+.?d*$/.test(val)) || (val == 0)) { return '0.00' } // Test for numeric, Return 0.00 if fail or '0'

var k = Math.pow(10,n); // Multiply 'val' by '10 to the power n'. 'Math.round' rounds to a whole number

val = (Math.round(val*
k)).toString(); // Convert to a string and insert the decimal point to keep trailing 0's

re = eval("/^(d+)(d{"+n+"})$/");

return val.replace(re,"$1.$2");

}

//-->

</script>

</head>



<body bgcolor="#ffffff">

<form name="report">

1. <input type="text" onChange="calc()"><br>

2. <input type="text" onChange="calc()"><br>

3. <input type="text" onChange="calc()"><br>

4. <input type="text" onChange="calc()"><br>

Total. <input name="total" type="text" readonly>

</form>

</body>

</html>
Copy linkTweet thisAlerts:
@timster69authorApr 17.2003 — Hey Doc, I seem to only be having this problem when I try to multiply .36 by multiples of 5 and 9. I need to calculate mileage expense, so I total the users miles traveled and then I mulitply that number by the current going rate (.36) per mile. That's what's killing me. Here's what I have:

function sum()

{

(document.expenseform.milescost.value) = parseFloat(document.expenseform.totalmiles.value) * .36;

(document.expenseform.milescost.value) = parseFloat((document.expenseform.milescost.value));

}

But that is not working with 5's and 9's. Why?
Copy linkTweet thisAlerts:
@DrDaMourApr 17.2003 — not working like it's what's giving you that 15 digits after the decimal?

anyways, i dind't know about the string.tofixed(2) member fucntion, you should probalby use that as long as you can cound on ie5 and later..

.36 * 5 = 1.80

.36 *
9 = 3.24

those don't seem that odd, you'd think they work fine. Upload the file or link it.
Copy linkTweet thisAlerts:
@timster69authorApr 18.2003 — Ok, but if you try to veiw this in your browser, kill the ODBC connection. That was just there so I could get a list of names from our source file.

[upl-file uuid=3d4a09bb-b6ca-4c05-a581-6a6a7d900df2 size=4kB]expense_report.zip[/upl-file]
Copy linkTweet thisAlerts:
@DrDaMourApr 18.2003 — sorry man i don't have asp, what i meant for you to send me was the html the browser sees. Just do a view source save as, and up that.
Copy linkTweet thisAlerts:
@timster69authorApr 18.2003 — You know what. I solved it using .asp. I just didn't want my users to panic when they saw a long string on their total figures. Now, I just have the server format the final number before sending it back to the client. Works great. Thanks again though for the "math" code.
×

Success!

Help @timster69 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...