Jump to content

Why does this simple Javascript return NaN


Guest Big Fish

Recommended Posts

Guest Big Fish

I'm completely new to learning JavaScript and i've just started learning functions and I'd like to know why this function returns NaN?

<html>
<title>Simple Calculator</title>
<head>
<script style="text/javascript">
<!--
function add(num1,num2)
{
	return (num1+num2);
}
function subtract (num1, num2)
{
	return (num1-num2);
}	
function multiply(num1,num2)
{
	return (num1*num2);
}
function divide (num1,num2)
{
	return (num1/num2);
}	
//-->
</script>
</head>
<body>
<h1>Simple Calculator</h1>
<form>
First Number: <input type="text" name="a" /><br/>
Second Number: <input type="text" name="b" /><br/>
<input type="button" value="Add" onclick="alert(add(parseInt(a),parseInt())"/>
</form>
</body>
</html>

Link to comment
Share on other sites

I thought I should follow up on this question, since no one else has answered it yet... I don't use Javascript a whole lot, but I don't believe you can get the values of "a" and "b" simply by calling them "a" and "b". (and besides, you've named the second input "b" but you refer to it in the Javascript code as "B".

 

Here is how I would approach it, by giving your inputs IDs and using getElementById():

 

<html>
<title>Simple Calculator</title>
<head>
<script style="text/javascript">
<!--
       function add(num1,num2)
       {
               return (num1+num2);
       }
       function subtract (num1, num2)
       {
               return (num1-num2);
       }       
       function multiply(num1,num2)
       {
               return (num1*num2);
       }
       function divide (num1,num2)
       {
               return (num1/num2);
       }       
//-->
</script>
</head>
<body>
<h1>Simple Calculator</h1>
<form>
First Number: <input type="text" name="a" id="a" /><br/>
Second Number: <input type="text" name="b" id="b" /><br/>
<input type="button" value="Add" onclick="alert(add(parseInt(document.getElementById ('a').value),parseInt(document.getElementById ('b').value)))"/>
</form>
</body>
</html>


Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...