[英]How do i use JavaScript to take the input from a text box to a variable then print the value of a variable?
I want to take the value of a text box and put it with a variable, then print the value of the variable as text on the page when a button is pressed.我想获取文本框的值并将其与变量放在一起,然后在按下按钮时将变量的值作为文本打印在页面上。 I'm using JavaScript and not using the form tag.
我正在使用 JavaScript 而不是使用表单标签。 So, how do I do this with what I have?
那么,我如何用我所拥有的来做到这一点?
my code:我的代码:
var x = document.getElementById("I1");
var y = document.getElementById("I2");
var z = x+y;
document.getElementById("B2").onclick = function myFunction2(){
documen.getElementById("H2").innerHTML = x;
}
If I understand you correctly, you'll simply want to grab the .innerHTML
from your <textarea>
, and assign that to x
.如果我理解正确,您只需从
<textarea>
获取.innerHTML
,并将其分配给x
。 Also note that you have documen
instead of document
inside of your click function.另外请注意,你有
documen
,而不是document
的点击函数中。
Note that you're probably also looking to output z
rather than x
.请注意,您可能还希望输出
z
而不是x
。 This will only work (the way you expect) if both x
and y
are integers, so it's also a good idea to run parseInt()
over the two values.如果
x
和y
都是整数,这只会工作(您期望的方式),因此对两个值运行parseInt()
也是一个好主意。
Here's a working example:这是一个工作示例:
var x = parseInt(document.getElementById("I1").innerHTML); var y = parseInt(document.getElementById("I2").innerHTML); var z = x + y; document.getElementById("B2").onclick = function myFunction2() { document.getElementById("H2").innerHTML = z; }
<textarea id="I1">1</textarea> <br /> <div id="I2">2</div> <br /> <button id="B2">Button</button> <br /> <br /> <div id="H2"></div>
Are I1
and I2
the ids of your textbox? I1
和I2
是您的文本框的 ID 吗? because to get the inside text you need to use因为要获取您需要使用的内部文本
var x = document.getElementById("I1").value;
You should rely on the value
attribute of the textarea instead of its innerHTML
attribute, and fetch that in the click event handler of the button.您应该依赖 textarea 的
value
属性而不是其innerHTML
属性,并在按钮的 click 事件处理程序中获取它。
document.getElementById("B2").onclick = function() { var x = document.getElementById("I1").value; document.getElementById("H2").innerHTML = x; }
<textarea id="I1">1</textarea> <br /> <button id="B2">Button</button> <br /> <br /> <div id="H2"></div>
document.getElementById("B2").onclick = function myFunction2(){ var x = Number(document.getElementById("I1").value); var y = Number(document.getElementById("I2").value); var z = x+y; document.getElementById("H2").innerHTML = z; }
<input type="text" id="I1" value="" /> + <input type="text" id="I2" value="" /> = <button id="B2"> ? </button> <span id="H2"> </span>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.