PDA

View Full Version : document.getElementById issue



svoirin
04-12-2006, 08:26 AM
I'm have a issue here. The "addnumb" is 25 and I'm trying to add it to the value of document.getElementById(total).innerHTML with is 1.95, but the alert box just appends the 25 to the end. The result is $1.9525. What am I doing wrong here. I've been at this for about 6 hrs now. Please help.

<div id="total">1.95</div>
function addCostBox(boxName,total,addnumb){
if(boxName.checked) {
var g = document.getElementById(total).innerHTML;
var a = g;
var b = addnumb;
var d = a + b;
alert('This option will add $'+d+' to your total.');
}
}

Thanks,
Shane

mwinter
04-12-2006, 10:09 AM
The "addnumb" is 25 and I'm trying to add it to the value of document.getElementById(total).innerHTML with is 1.95, but the alert box just appends the 25 to the end.As the innerHTML property evaluates to a string, the other operand is type-converted to a string, too. The result is concatenation rather than arithmetic addition.



function addCostBox(boxName, total, value) {
var element;

if (boxName.checked && document.getElementById
&& (element = document.getElementById(total))) {
alert('This option will add $'
+ (+element.innerHTML + value)
+ ' to your total.');
}
}
The unary plus (+) in the expression,



+element.innerHTML
coerces its operand to a number or NaN (Not-a-Number).

Mike