开发者

javascript (math) adding up an array

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");
al开发者_如何学编程ert(price)


This will take all input elements into account (useful if you have many). Filter them by type and get their values in loop:

var inputs = document.getElementsByTagName("input");
var total = 0;

for (var i = 0; i < inputs.length; i++){
    if (inputs[i].type = "text"){
        total += parseInt(inputs[i].value, 10);
    }
}

alert(total);


<input id="test1" type="text" name="test" value="300" />
<input id="test2" type="text" name="test" value="500" />

JS:

var price = parseInt(document.getElementById("test1").value, 10) + parseInt(document.getElementById("test2").value, 10);


<input id="price1" type="text" name="test" value="300" />
<input id="price2" type="text" name="test" value="500" />

This will work:

var price = document.getElementById("price1").value+document.getElementById("price2").value;
alert(price)

Note Do not have other tags with id="price1" or id="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 the id attribute. You haven't given your input elements an id attribute, so that's not going to work.

Secondly, document.getElementById('someId') returns an element, but you want the value. You can use the value property to get it:

var price1 = parseInt(document.getElementById("test1").value, 10);
var price2 = parseInt(document.getElementById("test2").value, 10);
alert(price1 + price2);

This will work with the following HTML:

<input type="text" name="test" id="test1" value="300" />
<input type="text" name="test" id="test2" value="500" />

Note the use of parseInt. The value property returns a String, so we use parseInt to attempt to parse that into a Number. If you don't use it, price1 + price2 will simply concatenate the strings.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜