0

It's simple addition in Javascript. But I don't understand why result is 1510 instead of 15+10.

<script>
function doCalc(){
    with (document.calc){
    sum1.value = orderin.value+ ordercheck.value
    }
}
</script>
<form method="post" name="calc" enctype="multipart/form-data">

    <input checked="checked" value="0" name="orderin" type="RADIO" onChange="doCalc()">+0
    <input value="15" name="orderin" type="RADIO" onChange="doCalc()">+15
    <br><br>
    <input id="ordercheck1" checked="checked" value="0" name="ordercheck" type="RADIO" onChange="doCalc()">+0
    <input id="ordercheck2" value="10" name="ordercheck" type="RADIO" onChange="doCalc()">+10
    <br><br>
    TOTAL: <input size="7" value="0" name="sum1" readonly="readonly" border="0">
    <input onClick="doCalc()" value="TOTAL" name="button" type="button">
</form>
Amit
  • 45,440
  • 9
  • 78
  • 110
  • 2
    this is javascript, not java. They are completely unrelated languages. Please change the title with the correct language. – PC Luddite Aug 04 '15 at 06:53
  • As suggested by @ThePcLuddite it has nothing to do with java , kindly remove java from tittle and body – Panther Aug 04 '15 at 06:55
  • related: http://stackoverflow.com/questions/13953939/how-to-force-addition-instead-of-concatenation-in-javascript – Ward D.S. Aug 04 '15 at 06:57

3 Answers3

1

Javascript variable can hold every type (string and a number). You are trying to add two strings. Try using this:

sum1.value = parseInt(orderin.value,10) + parseInt(ordercheck.value,10)

parseInt will try to turn a string into a number. The 10 indicates you want to turn the number into decimal scale. More about parseInt W3Schools or MDN.

Technotronic
  • 8,424
  • 4
  • 40
  • 53
0

By default output of input is string/literal in javascript, hence its getting concanated. You need to parse it into int.

 sum1.value = parseInt(orderin.value)+ parseInt(ordercheck.value)
Panther
  • 3,312
  • 9
  • 27
  • 50
0

You are trying to do + when one (or both) of your variables are considered a string. Make sure to always parseInt(variable) first when you aren't sure! Usually values selected from the DOM (user input from text fields and such) are considered strings.

// these are ints
var a = 5;
var b = 10;
var c = a + b; // c is 15

// notice the ""-notation, these are strings
var x = "5"; 
var y = "10";
var z = x + y; // z is 510

// just do this to fix it:
var z = parseInt(x) + parseInt(y) // z is 15

In your case:

sum1.value = parseInt(orderin.value) + parseInt(ordercheck.value)
Ward D.S.
  • 536
  • 3
  • 11