javascript - 从 html 表单获取 javascript 变量

标签 javascript html

我是编程新手。我正在尝试构建一个程序,以便当用户向表单提交 2 个整数时,它会输出总和。

这是我到目前为止得到的

<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>

最佳答案

您需要使用value 来获取输入的值:

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

并且该值将是一个字符串,因此您需要 parseInt 将其转换为整数:

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

关于javascript - 从 html 表单获取 javascript 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30384398/

相关文章:

javascript - 从 JSON 中检索键值

javascript - 仅当模态可见时 ESC 是否触发后退事件?

php - Bootstrap 表单到数据库

html - 将文本放在图像旁边

python - 我无法在 Django 模板上显示图像

javascript - Internet Explorer 8 按下按钮之间的延迟

javascript - 如何在 jquery 中添加多段的 "read more"链接?

javascript - D3 教程在本地计算机上不起作用

javascript - 从左到右动画宽度(带文字)

html - 如何使此左侧边栏在移动设备上可见?