I have been teaching myself some Javascript; and I am having trouble getting this function to run properly. This is what is being output.
Answer: [object HTMLInputElement][object HTMLInputElement]
function addNumbers() { var firstNum = document.getElementById("num1"); var secondNum = document.getElementById("num2"); result = firstNum + secondNum; document.getElementById("demo").innerHTML = "Answer: " + result; return result; }
<!DOCTYPE html> <html> <head> <!-- ,<script src="scripts.js"></script> --> </head> <body> <h2>JavaScript Functions</h2> <p>This example calls a function which performs a calculation and returns the result:</p> <form> First Number<br> <input type="text" name="firstNum" id="num1"><br> Second Number<br> <input type="text" name="secondNum" id="num2"><br> <input type="button" value="Add!" onclick="addNumbers()"> </form> <p id="demo"></p> </body> </html>
Like the comments said, get the value from the HTML element node and parse it into a float
var firstNum = parseFloat(document.getElementById("num1").value);
var secondNum = parseFloat(document.getElementById("num2").value);
function addNumbers() { var firstNum = parseFloat(document.getElementById("num1").value); var secondNum = parseFloat(document.getElementById("num2").value); result = firstNum + secondNum; document.getElementById("demo").innerHTML = "Answer: " + result; return result; }
<!DOCTYPE html> <html> <head> <!-- ,<script src="scripts.js"></script> --> </head> <body> <h2>JavaScript Functions</h2> <p>This example calls a function which performs a calculation and returns the result:</p> <form> First Number<br> <input type="text" name="firstNum" id="num1"><br> Second Number<br> <input type="text" name="secondNum" id="num2"><br> <input type="button" value="Add!" onclick="addNumbers()"> </form> <p id="demo"></p> </body> </html>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.