简体   繁体   中英

Getting input from a html textbox then putting it into a Javascript variable not working

This is my code. When I click the calculate button it is displaying just the number 35. WHere have I gone wrong and how can I fix it?

 <!doctype html> <html> <head> <title>JS Practise 2</title> </head> <body> <h1> Problem 1.1 </h1> <script language="javascript"> var topsoil_amount = 1; function calculate() { var topsoil_amount = document.getElementById(Input); var topsoil_cost = 15; var cost = (topsoil_amount * topsoil_cost) + 35; alert(cost); } </script> <br> <input type="text" name="Input" size="16" id="Input"> <input type="button" value="Calculate" onClick="calculate()"> </body> </html>

topsoil_amount is a DOM element, not a number. You need to reference the value. Secons issue is you need quotes around the id.

var topsoil_amount = document.getElementById("Input").value;

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM