Guest Big Fish Posted November 22, 2010 Report Posted November 22, 2010 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> Quote
falkencreative Posted November 23, 2010 Report Posted November 23, 2010 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> Quote
Recommended Posts
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.