FRIHOSTFORUMSFAQTOSBLOGSDIRECTORY
You are invited to Log in or Register a Frihost Account!

problem adding variables in javascript

 


ammonkc
I'm trying to do some simple calculations with javascript. but for some reason instead of calculating the values of the variables, it would just append the values together like a string.

for example:

if i'm trying to get something like this:
5 + 4 = 9;

i end up with something like this:
5 + 4 = 54;

as far as I can tell i'm declaring the variables right. i'm printing out two separate calculations, 'refund_amount' and 'air_total'. the first one (refund_amount) is calculating fine, but the latter is acting like a string and appending the values together.

here is the full function:

Code:
// JavaScript Document
//calculation to be done on the form
function calc () {
   var refund_amount;
   var air_total;
   
   refund_amount = document.getElementById('origPrice').value;
   if (document.form.refundIns[0].checked==true) {         
      refund_amount = refund_amount - document.getElementById('lessIns').value;
   }
   if (document.form.destSrv[0].checked==true) {         
      refund_amount = refund_amount - document.getElementById('destService').value;
   }
   
   
   air_total = document.getElementById('penaltiesAirSupplier').value +
   document.getElementById('penaltiesAirPanda').value;
   
   document.getElementById('refundAmt').innerHTML = refund_amount;
   document.getElementById('airTotal').innerHTML = air_total;
}//end calc () function
Atomo64
you have to use parseInt on the form fields values, then everything is going to work fine
ammonkc
thanks. I actually just got it to work by converting the form field values to numbers like this:

var num = document.getElementById('num').value *1;

then everything work fine. I'm guessing that parseint does the same thing. is it better to use parseint instead of the way that i did it? thanks.
kv
Yes, It is better. It might not change the results, but definitely it increases readability.
Reply to topic    Frihost Forum Index -> Scripting -> Php and MySQL

FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2007 Frihost, forums powered by phpBB.