views:

53

answers:

3

I have two textboxes Num1 and Num2 and another textbox Sum having the value 10.

How can I do this wherein if the user will enter a number for Num1, it will add it to Sum and dynamically change the displayed number in the Sum textbox. If the user will enter a number in Num2 it will also add that number to the updated number shown in Sum textbox and dynamically change the value for Sum textbox also.

How to do this in Javascript?

+3  A: 
<input type="text" id="Num1" name="Num1"/>
<input type="text" id="Num2" name="Num2"/>
<input type="text" id="Sum" name="Sum"/>


function addNums() {
  var num1 = parseInt(document.getElementById('Num1').value,10);
  var num2 = parseInt(document.getElementById('Num2').value,10)
  document.getElementById('Sum').value = (num1 + num2).toString();
}

There are other ways to reference the form items, but this one works.

Robusto
If the "addNums" function is called repeatedly, say with `setInterval`, then the sum can update regularly. This is better than depending on the "onchange" handler of input elements, which can fire at unexpected times for the user (e.g. after focus is changed, instead of when the user "finishes" typing).
maerics
@maerics: I think you meant this comment for @jtp's response. He's the one talking about onchange handlers. The scope of my reply had nothing to do with when the function gets called, it merely illustrated the mechanics of adding numerical values in input elements.
Robusto
@maerics - Good point for onchange event. Even with its browser quirks, it is technically a semantic error in this case since inputting the same value will not update sum.
jtp
@Robusto - sorry my comment was confusing, I was trying to explain how your mechanics could be combined with a trigger that makes it more robust than a solution that uses "onchange" handlers. (+1)
maerics
+2  A: 

Something like that:

<input type="text" id="Num1" value="1" onblur="recalculateSum();"/>
<span>+</span>
<input type="text" id="Num2" value="1" onblur="recalculateSum();"/>
<span>=</span>
<input type="text" id="Sum" value=""/>
<script>

    function recalculateSum()
    {
        var num1 = parseInt(document.getElementById("Num1").value);
        var num2 = parseInt(document.getElementById("Num2").value);
        document.getElementById("Sum").value = num1 + num2;

    }

</script>
Taras B
theres a problem because when I use '+' it will concatenate.
anonymous
it won't. There's parseInt.
Taras B
+4  A: 
jtp
personally, this is cleanest
ScottSEA
Thanks @ScottSEA. Though after reading the comments from maerics and Robusto, I went with the onblur event instead since onchange won't update sum if the same number is entered into the input field. :)
jtp