简体   繁体   English

在Javascript中使用文本框的“ .value”属性

[英]Using the “.value” property of a textbox in Javascript

document.getElementById("t3").value = document.getElementById("t1").value + 
                                      document.getElementById("t2");

Through above code I could not get the result of addition of two numbers. 通过以上代码,我无法获得两个数字相加的结果。

If you want to add those to values, you have to convert them to integer at first. 如果要将这些值添加到值,则必须首先将它们转换为整数。 .value always holds a string. .value始终包含一个字符串。

parseInt(document.getElementById("t1").value, 10) + parseInt(document.getElementById("t2").value, 10);

You are not actually adding two numbers together. 您实际上并没有将两个数字相加。 You are attempting to add document.getElementById("t1").value (which is a string containing with numbers in it) to document.getElementById("t2") , which is a DOM element. 您尝试添加document.getElementById("t1").value (这是它与数字包含字符串) document.getElementById("t2")这是一个DOM元素。

You probably get a result like this: 您可能会得到如下结果:

43[object HTMLInputElement]

You need to (a) get the value property of the second element and (b) add them together as numbers, rather than as strings. 您需要(a)获取第二个元素的value属性,并且(b)将它们作为数字而不是字符串加在一起。

document.getElementById("t3").value = (+document.getElementById("t1").value) + 
                                      (+document.getElementById("t2").value);

(+document.getElementById("t1").value) converts the value into a number. (+document.getElementById("t1").value)将值转换为数字。 It is the unary plus + operator . 它是一元加号+运算符

Try this: 尝试这个:

document.getElementById("t3").value = parseInt(document.getElementById("t1").value,10) + 
                                  parseInt(document.getElementById("t2").value,10);

This is cheeky, but on the off-chance the t3 element that the OP is trying to update is a div or span rather than an input :) 这很厚脸皮,但是在偶然的情况下,OP试图更新的t3元素是divspan而不是input :)

var t1, t2, t3;

t1 = document.getElementById("t1");
t2 = document.getElementById("t2");
t3 = document.getElementById("t3");

t3.innerHTML = parseInt(t1.value, 10) + parseInt(t2.value, 10);

Or 要么

t3.innerHTML = +t1.value + +t2.value;

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

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