javascript(数学)将数组相加
我有两个 javascript 文本框。
<input type="text" name="test" value="300" />
<input type="text" name="test" value="500" />
如何使用 javascript 来提醒文本框中商品的总价?
像这样的东西会起作用吗?
var price = document.getElementById("test");
alert(price)
I have two javascript text boxes.
<input type="text" name="test" value="300" />
<input type="text" name="test" value="500" />
How can I use javascript to alert the total price of the items in the text box?
Would something like this work?
var price = document.getElementById("test");
alert(price)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这将考虑所有
input
元素(如果有很多元素,这很有用)。按type
过滤它们并在循环中获取它们的值:This will take all
input
elements into account (useful if you have many). Filter them bytype
and get their values in loop:JS:
JS:
这将起作用:
注意不要有其他带有
id="price1"
或id="price2"
的标签This will work:
Note Do not have other tags with
id="price1"
orid="price2"
由于多种原因,您所写的内容不会起作用。首先,顾名思义,
getElementById
根据id
属性的值获取元素。您还没有为您的input
元素提供id
属性,因此这不起作用。其次,
document.getElementById('someId')
返回一个元素,但您需要该值。您可以使用value
属性来获取它:这将适用于以下 HTML:
请注意
parseInt
的使用。value
属性返回一个字符串,因此我们使用parseInt
尝试将其解析为数字。如果您不使用它,price1 + Price2
将简单地连接字符串。What you have written will not work, for several reasons. Firstly, as the name suggests,
getElementById
gets an element based on the value of theid
attribute. You haven't given yourinput
elements anid
attribute, so that's not going to work.Secondly,
document.getElementById('someId')
returns an element, but you want the value. You can use thevalue
property to get it:This will work with the following HTML:
Note the use of
parseInt
. Thevalue
property returns a String, so we useparseInt
to attempt to parse that into a Number. If you don't use it,price1 + price2
will simply concatenate the strings.