Click to See Complete Forum and Search --> : [RESOLVED] Javascript - Adding Form Fields


darylr
05-12-2007, 05:30 PM
Hi folks,

Really sorry - this is probably the most basic javascript coding but Ive just started as part of a planner that calculates values using values in different form fields.

I cant however, get form field 1's value to add with form field 2's value.

eg.

A=10
B=12

When I try put A+B together in C, it displays "1012" instead of "22".

I know this is probably absolute basic JS, but can anyone give me some pointers please? :rolleyes:


<script type="text/javascript">
function convert(fuel)
{
A=document.form1.f1.value
F=document.form1.f1.value * 1.15
G=document.form1.f2.value=Math.round(F)
T=document.form1.tblock.value=Math.round(A+G)


}
</script>

Thanks.

Roger Ramjet
05-13-2007, 02:11 AM
The reason it is doing that is because the '10' and '12' are strings and so the + concatenates them into '1012'. You first have to convert them into numbers using paresInt (http://www.webreference.com/javascript/reference/core_ref/toplev.html#1064173), parseFloat (http://www.webreference.com/javascript/reference/core_ref/toplev.html#1064132), or Number (http://www.webreference.com/javascript/reference/core_ref/toplev.html#1064092). You will then find that + will add the numbers as you want.

darylr
05-13-2007, 03:33 PM
Sorted! Knew it would be something basic! :D

Thanks RR!

bradgrafelman
05-14-2007, 01:14 AM
Don't forget to mark this thread resolved.