Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Javascript String Help

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
I am trying to make a javascript that calculates an estimate for my clients. What I am doing is I have a form, and I have no problem converting the form input to strings, but once I have them as strings, when I add them, it LITERALLY adds them. Example:

variableone = document.form.formfield.value (this works fine)

variabletwo = document.form.formfield2.value (this works fine)

Next I declare a new variable equalling 0:

totalcost = 0;

but when I add the first two together:

(assuming that variableone calculates as 1 and that variabletwo calculates to 2 from the user input)

I put:

totalcost = variableone + variabletwo3

alert("The total cost is "+totalcost+" .")

but instead of alerting "3" and adding the string intergers, it comes up with "12" becasue its LITERALLY adding the two together.

If this was too confusing, email me at jeffmorrison@att.net and I'll upload the page so you can look at my source.

Thanks!!!
 
Try using the Number() function to change a string into a number:


<SCRIPT LANGUAGE=&quot;JavaScript&quot;>
<!--Begin

// Convert string to a number using Number()
var variableone = Number(document.form.formfield.value);
var variabletwo = Number(document.form.formfield2.value);

// Next I declare a new variable equalling 0:
var totalcost = 0;

// Set total cost to equal the v1 + v2;
totalcost = variableone + variabletwo;

// Alert total cost
alert(&quot;The total cost is &quot;+totalcost+&quot; .&quot;);


//End-->
</SCRIPT>
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top