Furlab
Furlab

Reputation: 43

Javascript increment operator

totalvalue = 0;
for (x=1; x<6; x++)
{
totalvalue += document.getElementById("rcv_amount_"+x).value;
}

rcv_amount_1 = 2 rcv_amount_2 = 4 rcv_amount_3 = 6

expected result is 12, but i am getting 0246.

Any help?

Upvotes: 1

Views: 95

Answers (2)

makmonty
makmonty

Reputation: 465

Try with

totalvalue += parseInt(document.getElementById("rcv_amount_"+x).value, 10);

Upvotes: 0

Alnitak
Alnitak

Reputation: 339776

You have to convert the .value into a number - initially the .value property of an <input> element is a string, so the += operator results in concatenation, not addition.

To convert a string value into a number you can use parseInt(..., 10) for integers, or parseFloat(...) or just +(...) for non-integers.

Upvotes: 6

Related Questions