PDA

View Full Version : i need help...how to add 2 number...javascript



doctor javascript
11-15-2006, 10:27 AM
for example,

<html>
<head>
<script language="JavaScript">
function apple()
{
a=2;
b=2;
c=a+b;

document.write("The answer is ", c);

}
</script>
</head>
<body>
<h1> Calculate </h1>
<form name="form1">
<input type="button" value="Calculate" onClick="apple()">

</form>
</body>
</html>

The frustrating part is the answer is 22 instead of 4. Please help me. I am so frustrated!!!

Twey
11-15-2006, 04:18 PM
<script language="JavaScript">language is deprecated; type is required.
a=2;You omitted the var keyword. If you intend to create globals, please create them in the global scope.
document.write("The answer is ", c);You can't document.write() after the page has loaded without destroying the current page. Also, document.write() accepts only one argument.
<script type="text/javascript">
function apple() {
var a = 2,
b = 2,
c = a + b;
document.getElementById("apple_op").firstChild.nodeValue = "The answer is " + c;
return false;
}
</script>
</head>
<body>
<h1>Calculate</h1>
<p id="apple_op"> </p>
<form action="" onsubmit="return apple();">
<input type="submit" value="Calculate">
</form>
</body>

mwinter
11-15-2006, 04:36 PM
document.getElementById("apple_op").firstChild.nodeValue = "The answer is " + c;

...

<p id="apple_op"> </p>

You cannot assume that the text node will exist, and indeed in MSIE it does not, causing an error.

Mike

Twey
11-15-2006, 05:05 PM
Oops, indeed so, my error.
<script type="text/javascript">
function apple() {
var a = 2,
b = 2,
c = a + b,
op = document.getElementById("apple_op");
if(op.firstChild)
op.firstChild.nodeValue = "The answer is " + c;
else
op.appendChild(document.createTextNode("The answer is " + c));
return false;
}
</script>
</head>
<body>
<h1>Calculate</h1>
<p id="apple_op"> </p>
<form action="" onsubmit="return apple();">
<input type="submit" value="Calculate">
</form>
</body>