PDA

View Full Version : Problems with a simple math calculation.


Zapcat
09-23-2002, 12:18 PM
I am creating a simple form for ordering a product. I have 4 text boxes which will have values in, with a 5th having the total of all the other boxes.

My problem is this - I cannot get the amounts to add up and appear in the final box. I think it's because it's a text boxes these are figures. It's probably a typical newbie problem but can anyone suggest some code that will make this work?

ZapCat:)

glenngv
09-23-2002, 12:47 PM
var num1 = document.yourformname.yourfieldname1.value;
var num2 = document.yourformname.yourfieldname2.value;
alert(parseInt(num1)+parseInt(num2));

Zapcat
09-23-2002, 03:24 PM
Thanks for the code. Can anyone suggest how I do the following -

1. Deliver the total amount to a text box rather than an alert box

2. Ensure that the calculation is done when the page loads and is immediately updated should values in the text boxes change.

Hope you can help!

ZapCat :)

adios
09-23-2002, 04:23 PM
<html>
<head>
<script type="text/javascript" language="javascript">

function update() {
var f = document.f1, total = 0, addfields = new Array('t1','t2','t3','t4');
for (var i=0; addfields[i]; i++)
if (isNaN(parseFloat(f[addfields[i]].value))) {
alert('Please enter a valid number.');
f[addfields[i]].focus();
f[addfields[i]].select();
return;
} else {
total += parseFloat(f[addfields[i]].value);
f.total.value = total;
}
}

onload = update;

</script>
</head>
<body>
<form name="f1">
<input name="t1" type="text" size="12" value="124"
onblur="update()"><br>
<input name="t2" type="text" size="12" value="45"
onblur="update()"><br>
<input name="t3" type="text" size="12" value="8"
onblur="update()"><br>
<input name="t4" type="text" size="12" value="77"
onblur="update()"><br><br>
<input name="total" type="text" size="12"><br>
</form>
</body>
</html>

beetle
09-23-2002, 04:53 PM
adios's script should work perfectly. But, I suspect that you will want all of your values to be rounded decimals with 2 places. Use either of these functions to affect yout output numbers/*I didn't write this function but it works pretty well, however,
it returns the data as a string, so you can't perform any mathematical caclulations upon the returned data.
Just use it for output/display */
function currency(anynum)
{
//-- Returns passed number as string in $xxx,xxx.xx format.
anynum=eval(anynum)
workNum=Math.abs((Math.round(anynum*100)/100));workStr=""+workNum
if (workStr.indexOf(".")==-1){workStr+=".00"}
dStr=workStr.substr(0,workStr.indexOf("."));dNum=dStr-0
pStr=workStr.substr(workStr.indexOf("."))
while (pStr.length<3){pStr+="0"}

//--- Adds comma in thousands place.
if (dNum>=1000) {
dLen=dStr.length
dStr=parseInt(""+(dNum/1000))+","+dStr.substring(dLen-3,dLen)
}

//-- Adds comma in millions place.
if (dNum>=1000000) {
dLen=dStr.length
dStr=parseInt(""+(dNum/1000000))+","+dStr.substring(dLen-7,dLen)
}
retval = dStr + pStr
//-- Put numbers in parentheses if negative.
if (anynum<0) {retval="("+retval+")"}
return "$"+retval
}
/* This function I wrote to accompany parseInt and parseFloat but make it a bit more refined.
You can pass it a 2nd parameter that will round the decimal to that many places (default is 2).
Since the value returned is a number, you can use the result in mathematical calcuations */
function parseDecimal(decimal,zeros) {
if (typeof zeros == 'undefined') zeros = 2;
var mult = "1";
for (var i=0; i<zeros; i++)
mult += "0";
mult = parseInt(mult);
decimal=decimal.replace(/[a-zA-Z\!\@\#\$\%\^\&\*\(\)\_\+\-\=\{\}\|\[\]\\\:\"\;'\<\>\?\,\/\~\`]/g,"");
while (decimal.indexOf(".") != decimal.lastIndexOf("."))
decimal=decimal.replace(/\./,"");
return parseFloat(Math.round(decimal*mult)/mult);
}

Zapcat
09-23-2002, 05:03 PM
Can anyone explain Adios code? It works perfectly but I can't fathom it so I'm struggling to use it in my code. It'll also help me to improve my Jscript knowledge!!

Thanks to everyone who has helped so far!!

ZapCat :)

adios
09-23-2002, 05:12 PM
Adios explain. ;)

function update() {
var f = document.f1 //form reference
total = 0 //holds - the total!
addfields = new Array('t1','t2','t3','t4') //the four field names, to be 'plugged into' the form reference (saves code)
for (var i=0; addfields[i]; i++) //loop through addfields array - the conditional (addfields[i]) stops the loop when we're out of array elements, in this case addfields[4]
if (isNaN(parseFloat(f[addfields[i]].value))) { //check input
alert('Please enter a valid number.');
f[addfields[i]].focus();
f[addfields[i]].select();
return;
} else {
total += parseFloat(f[addfields[i]].value); //entry OK - add it it to total (+=)
f.total.value = total; //write to field
}
}

onload = update; //do it onload, no parentheses since you're assigning, not running it


That'll be $12.00.

beetle
09-23-2002, 05:17 PM
Sure, here's a play-by-playfunction update() {
// Initializes variables
var f = document.f1, total = 0, addfields = new Array('t1','t2','t3','t4');

// Loops through addfields array
for (var i=0; addfields[i]; i++)

// Check to see if the value in the current (from loop) field is a number
if (isNaN(parseFloat(f[addfields[i]].value))) {
/* The following code runs because the value IS NOT a number */
// Prompts user to repair the data
alert('Please enter a valid number.');

// Sets cursor focus to field
f[addfields[i]].focus();

// Selects the value in the field
f[addfields[i]].select();

// Breaks from the function
return;
}
else {
/* The following code runs becase the value IS a number */
// Increments total by the value of the field
total += parseFloat(f[addfields[i]].value);

// Outputs the total into the 'total' field in the form
f.total.value = total;
}
}

// Runs the update function when the page loads
onload = update; Oh, and I want $11.95 for mine :D

Zapcat
09-23-2002, 05:31 PM
Thanks everyone!! The cheques are in the post.:thumbsup: