简体   繁体   English

无法将文本框的值分配给变量

[英]Cannot assign the value of a textbox to a variable

I'm trying to read the value from a textbox and it returns nothing.我正在尝试从文本框中读取值,但它什么都不返回。

Within the console, it simply shows a white line, with the line number of the console.log statement.在控制台中,它只显示一条白线,带有console.log语句的行号。

 var amount = document.getElementById("billAmt").value; document.getElementById('calculate').addEventListener('click', function() { console.log(amount); });
 <input id="billamt" type="text" placeholder="Bill Amount"> <button type="button" id="calculate">Calculate!</button>

There are couple of issues in your code:您的代码中有几个问题:

  1. Typo in billamt . billamt错字。 It should be billAmt in HTML or change either of them to make same它应该是 HTML 中的billAmt或更改它们中的任何一个以使其相同
  2. You need to get the value inside the click function.您需要获取click函数中的值。

 document.getElementById('calculate').addEventListener('click', function() { var amount = document.getElementById("billAmt").value; console.log(amount); });
 <input id="billAmt" type="text" placeholder="Bill Amount"> <button type="button" id="calculate">Calculate!</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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