Forum Moderators: open

Message Too Old, No Replies

Dom sum all total

         

nanat

10:53 am on Nov 22, 2009 (gmt 0)

10+ Year Member



how can i add all A+B+C=D? sory i newbie in DOM

<script type="text/javascript">
function total(n)
{
var A = document.getElementById('input1').value;
var B = document.getElementById('inpit2').value;
var c = document.getElementById('inpit3').value;
var D = A + B +C;

document.getElementById('result').value = D;

}
</script>
</head>

<body>
input: <input type="text" id="input1" name="input1" onChange="total(1)"/>
<br />
input2: <input type="text" id="inpit2" name="inpit2" onChange="total(1)" />
<br />
input3: <input type="text" id="inpit3" name="inpit3" onChange="total(1)" />
<br />
<input type="text" id="result" name="C1" readonly="readonly"/>

daveVk

11:41 am on Nov 22, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Looks good to me, make sure you have "C" not "c" here

var C = document.getElementById('inpit3').value;

Does it not no anything ?

nanat

12:00 pm on Nov 22, 2009 (gmt 0)

10+ Year Member



as i expected hi daveVk ^^.. but dave it only add string statement like 3+3+3 =333 how about u some it up like 3+3+3 =6

var E =sum(A+B+C)?

rocknbil

8:14 pm on Nov 22, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



some it up like 3+3+3 =6

Well, I would hope you wouldn't get that as a total. :-)

You're experiencing the problem with the + being the same operator for both string concatenation and math. You may have to parseInt/parseFloat on setting A, B, and C, but parseInt() on the final value should be all that's necessary.

var D = parseInt(A+B+C);

if it doesn't work, try

var D = parseInt(parseInt(A)+parseInt(B)+parseInt(C));

if you're dealing with decimal numbers, it gets worse -

var D = ((A*100)+(B*100)+(C*100))/100;

usually works. But sometimes you get some wierd math due to floating point precision =previous thread [webmasterworld.com].

One has to wonder, though, why you are passing 1 (n) to the function?

nanat

12:41 am on Nov 23, 2009 (gmt 0)

10+ Year Member



tnx rocknbill..[Bow].. i forgot to erase (1) inside the total supposed to be that label 1 is for my multiplication method.

document.getElementById('result'+n).value = A*B;

daveVk

1:12 am on Nov 23, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



If you are using parseInt, then use parseInt(A,10) instead of just parseInt(A), parseInt( "010" ) for example gives 8.

Also there is little point in doing parseInt after the horse has bolted as in parseInt(A+B+C);

Best practice is probably to do it up front eg
var A = parseInt(document.getElementById('input1').value,10);