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 bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do you add 2 var's from Form input

Status
Not open for further replies.

rampage60

IS-IT--Management
Jul 1, 2002
73
NO
If I input 500 in both fields it returns 500500 not 1000 even if I am telling it to add them togather. If I replaced the + with * it will multiply correctly. Won't it to return 1000 when I input 500 in both fields. Need help please.

Big time Javascript newbie! Thanks!

<SCRIPT LANGUAGE=&quot;javascript&quot;>
function add()
{
var sum01 = document.george.start01.value;
var sum02 = document.george.finish01.value;
var sum = sum01 + sum02;
document.george.total01.value = sum;
}
</script>

<div align=&quot;center&quot;><form name=&quot;george&quot;>


Start <input type=text name=&quot;start01&quot; size=&quot;4&quot;>
Finish <input type=text name=&quot;finish01&quot; size=&quot;4&quot;>
Total <input type=text name=&quot;total01&quot; size=&quot;4&quot;>

<p><input type=&quot;button&quot; value=&quot;Do It&quot; onClick=&quot;add()&quot;></div></p>
</form>
 
No sweat, Javascript is simply interpreting your values as Strings and adding them together as strings (ie concatenating the two strings together).

To force javascript to treat numeric values properly, you should make use of either the parseInt(value) or parseFloat(value) functions.

Your code slightly modified:
[tt]
<SCRIPT LANGUAGE=&quot;javascript&quot;>
function add()
{
var sum01 = document.george.start01.value;
var sum02 = document.george.finish01.value;
var sum = parseInt(sum01) + parseInt(sum02);
document.george.total01.value = sum;
}
</script>

<div align=&quot;center&quot;><form name=&quot;george&quot;>


Start <input type=text name=&quot;start01&quot; size=&quot;4&quot;>
Finish <input type=text name=&quot;finish01&quot; size=&quot;4&quot;>
Total <input type=text name=&quot;total01&quot; size=&quot;4&quot;>

<p><input type=&quot;button&quot; value=&quot;Do It&quot; onClick=&quot;add()&quot;></div></p>
</form>
[/tt]

Of course if you expect to be recieving floating point numbers (ie 500.2 rather than 500) you should replace parseInt with parseFloat.
 
Thanks alot dwarfthrower!!! I am teaching myself javascript so I may design some functional intranet web pages for my company. ie. Mileage expense form. I have been developping website for years but just never got into javascript untill now. I would just hack others scripts for my use. Again thnx!

JS Newbie...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top