How can I add form values ​​using javascript?

this is the code that I came up with, but all it does is 1 + 1 = 11, I need it to do 1 + 1 = 2.

<head> <script type="text/javascript"> function startCalc(){ interval = setInterval("calc()",1); } function calc(){ one = document.form1.quantity.value; two = document.form1.price.value; c = one + two document.form1.total.value = (c); } function stopCalc(){ clearInterval(interval); } </script> </head> <body> <form name="form1"> Quantity: <input name="quantity" id="quantity" size="10">Price: <input name="price" id="price" size="10"><br> Total: <input name="total" size="10" readonly=true><br> <input onclick="startCalc();" onmouseout="stopCalc()" type="button" value="Submit"> </form> </body> 

Of course, this is a really simple form, but you get the idea, please help me tell you what I'm doing wrong here.

+4
source share
5 answers

You need to use parseInt() to convert the string to an integer.

 c = parseInt(one, 10) + parseInt(two, 10) 
+6
source

use this

 c = parseInt(one,10) + parseInt(two, 10); 
+3
source

You need to convert the price values ​​to numeric.

use parseFloat for the price, since it can have decimal values.

use parseInt with a base.

e, g:

 function calc(){ one = parseInt(document.form1.quantity.value, 10); two = parseFloat(document.form1.price.value); c = one + two document.form1.total.value = (c); } 
+2
source

You can use + to convert a string to a number (integer or floating)

 c = +one + +two; 
+1
source

You can use this

  one = document.form1.quantity.value/1; two = document.form1.price.value/1; 
0
source

Source: https://habr.com/ru/post/1340736/


All Articles