简体   繁体   中英

Getting from html form to javascript variable

I'm new to programming. I'm trying to build a program so when a user submits 2 integers into the form, it outputs the sum.

Here's what I got so far

<html>
<h1> The Adder </h1>
<form>
  Enter your first number<input type="text" id='a'> <br>
  Enter your second number<input type="text"id='b' <br>
  <input type= "button" onclick='add()' value="Submit"/>
</form>
<script>
function add(){
    var avalue= document.getElementById('a');
    var bvalue= document.getElementById('b');

    alert(avalue+bvalue); 
}
</script>
</html>

You need to use value to get the value of the input:

var avalue= document.getElementById('a').value;

And the value will be a string, so you'll need parseInt to convert it to integer:

var avalue= parseInt(document.getElementById('a').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