Forum Moderators: open
My forms themselves are handling the calculations just fine, but when I take the resulting values of the individual forms and attempt to add them together into a new form I am getting concatenated values and not the simple addition I seek.
This is the code for the final form:
function total() {
document.ftotal.totalans.value=eval(document.fhomee.heans.value)+(document.fhomeg.hgans.value)+(document.ftransv.vans.value)+(document.ftransf.fans.value);
}
So my 4 initial calcs breakdown thus:
document.fhomee.heans.value = 8
document.fhomeg.hgans.value = 10
document.ftransv.vans.value = 7
document.ftransf.fans.value = 3
When running the function total() I am getting the following:
document.ftotal.totalans.value = 81073
and not 28
i know it is a simple problem, i just need a punt in the right direction.
tia,
jojo
When I multiply each individual calculation by 1
function total() {
document.ftotal.totalans.value=eval((document.fhomee.heans.value)*1 +(document.fhomeg.hgans.value)*1 +(document.ftransv.vans.value)*1 +(document.ftransf.fans.value)*1 );
}
I get my 28. So basically i am forcing my string into an int but am not sure how to go about setting the calc results as ints in the first place, so i wouldn't need to force by *1.
tia,
jojo
<script type="text/javascript">
foo = "2";
bar = "5";
alert(foo + bar);
alert( (foo * 1) + (bar * 1) );
alert( eval(foo + '+' + bar) );
</script>
function total() {
document.ftotal.totalans.value =
parseInt(document.fhomee.heans.value,10) + parseInt(document.fhomeg.hgans.value) + parseInt(document.ftransv.vans.value) + parseInt(document.ftransf.fans.value);
}
You might want to add some checks first though to make sure none of those return NaN.
If, for purposes of self-documentation, this leaves intentions unclear, I use the
Number constructor as a straightforward parsing function - with the same effect. <but>
It ain't perfect either. (even more unlikely) Strings of the form "0x[0-9a-f]" will be considered as hex.
</but>
[edited by: Bernard_Marx at 4:44 pm (utc) on June 19, 2007]
function total() {
document.ftotal.totalans.value =
parseInt(document.fhomee.heans.value, 10) + parseInt(document.fhomeg.hgans.value, 10) + parseInt(document.ftransv.vans.value, 10) + parseInt(document.ftransf.fans.value, 10);
}
I think that in a scenarios such as calculating form input the intent is so self-evident that
*1 becomes a "pattern" - one that actually allows the remaining logic to be expressed more clearly. That said, explicit intent can be assured, if necessary, by using Number. The probability of the input consisting of digits prefixed by "0x" is so minimal that it would almost require willful misbehaviour on the part of the user.
parseInt¦parseFloat can be tripped up by the "unlikely", whilst Number can be tripped up by the "very unlikely". Ooh! My argument is so weighty it almost falls off the page.