Forum Moderators: open
<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"/>
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?
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);