Ridiculously simple JS calculation problem

Soldato
Joined
27 Dec 2005
Posts
17,316
Location
Bristol
I'm just trying to do a simple JS addition, but it's treating one of the vars as a string and I don't know to adjust this.

Code:
var baseprice = 12;
var packaging = document.getElementById("packaging");
totalprice = baseprice + packaging.value;
document.getElementById("totalprice").innerHTML = "£" + totalprice + ".00"

If packaging.value is 3 then it outputs 123. If I replace the + with a - or * then it works fine (ie outputs 9 and 36 respectively).

This is probably so simple that I doubt I need to explain any more, but it's doing my nut in. Cheers.
 
the packaging.value is being interpreted as a string. If you explicitly state that packaging.value is an integer you'll fix the problem:

Code:
totalprice = baseprice + parseFloat(packaging.value);
 
Back
Top Bottom