4

this is the code i came up with but all it does is this 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 what i'm doing wrong here

5 Answers 5

6

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

c = parseInt(one, 10) + parseInt(two, 10)
Sign up to request clarification or add additional context in comments.

3 Comments

The second parameter, 10, is the base (i.e. base-10, decimal). While it's the default base, it's good to specify it anyway, and jslint will complain if you don't.
YES! it worked your the best! i'm fairly new to javascript so thats why i make dumb mistakes ;)
Isn't the +one + +two notation simpler?
3

use this

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

1 Comment

close, but don't forget the radix parameter or you can get some odd results.
2

You need to convert the price values to numeric.

use parseFloat for price since it can have decimal values.

use parseInt with the radix.

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);
}

Comments

1

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

c = +one + +two;

Comments

0

You can use this

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.