Forum Moderators: open
I have an online order form. The price of each item is in a textbox. For the user's convenience, I'd like a javascript that adds the grand total and then writes it to a textbox. Observe:
function total() {
var a=Number(document.getElementById("a").value);
var b=Number(document.getElementById("b").value);
var c=Number(document.getElementById("c").value);
var grandtotal=a+b+c;
document.getElementById("total").value=grandtotal.toFixed(2);
}
The textbox "total" is supposed to be the total of textboxes "a", "b", and "c". Textbox "total" should only be updated when the function total() is run.
I'm sure it's some stupid mistake, but why won't this work?
alert("grandtotal");That alerts the literal text "grandtotal", not the number.
I have discovered the most unorthodox solution. The total() function will be called from within other functions. For testing purposes, I had called it via button:
<input type="button" value="Total" onClick="total()" />
But when I call it from within other functions, it works just fine. Most bizzare?
That is a little weird that it would work that way.... perhaps if you went like this for the button
<input type="button" value="Total" onClick="total(); return false;" />
The reason could be that clicking a button is submitted the page and so it does run the JS and set that value but then the page reloads and undoes the grand total value.
Adding the "return false;" will tell it just to run the javascript and not to submit the page.
[edited by: Demaestro at 7:30 pm (utc) on July 7, 2008]
Using total, in FF error console:
Error: total is not a function
Source File: ....test.html
Line: 1
Because total is a form element. Added simple isNaN check, be sure to change the ¦ for logical "or" pipes.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<!-- doctype on one line -->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Untitled</title>
<script type="text/javascript">
function total() {
var a=Number(document.getElementById("a").value);
var b=Number(document.getElementById("b").value);
var c=Number(document.getElementById("c").value);
if (isNaN(a) ¦¦ isNaN(b) ¦¦ isNaN(c)) { alert("Please enter only numbers."); return false; }
var grandtotal=a+b+c;
document.getElementById("tot").value=grandtotal.toFixed(2);
return false;
}
</script>
</head>
<body>
<form onSubmit="return total();">
<p><label for="a">A:</label> <input type="text" name="a" id="a" onChange="total();" value="0"></p>
<p><label for="b">B:</label> <input type="text" name="b" id="b" onChange="total();" value="0"></p>
<p><label for="c">C:</label> <input type="text" name="c" id="c" onChange="total();" value="0"></p>
<p><label for="tot">TOTAL:</label>
<input type="text" name="tot" id="tot" onFocus="this.blur();" value=""></p>
<p><input type="submit" name="s" id="s" value="Get Total"></p>
</form>
</body>
</html>