Jake
Jake

Reputation: 1637

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");
alert(price)

Upvotes: 1

Views: 3213

Answers (4)

Igor Dymov
Igor Dymov

Reputation: 16460

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);

Upvotes: 1

James Allardice
James Allardice

Reputation: 166021

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.

Upvotes: 0

Sherif elKhatib
Sherif elKhatib

Reputation: 45942

<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"

Upvotes: 0

Dogbert
Dogbert

Reputation: 222268

<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);

Upvotes: 0

Related Questions