Add two numbers

This tutorial demonstrates how to get two inputs from the user within a HTML page and have a button on the page to call a javascript method to process the inputs and alter the answer output on the web-page.

Within HTML, there are input tags that allow the user to input data that is passed either to a javascript method to validate the inputs (for example a registration forum) or to pass data back to the server (after the validation has taken place if required).

The value 1 input is defined as
value 1 = <input type=’text’ id=value1 name=’value1′ value=’1’/>
the input type is text, which means any textual value, [A-Z]*[0-9]* but in this case since just adding integers [0-9] would be the required input.
The id is for getting the value from the input with using javascript document.getElementById, value is for setting the default value.

The function within the javascript, addNumbers() will get the inserted value1 by using the javascript document object. Within this object there is a method called getElementById that returns back the object, which in turn using the .value of the object returned can be passed to the parseInt (which converts a string value into a integer value). The same method is used for the answer input within the web-page (getElementById) but assign the return object to a variable allows access to the .value to set the value on the web-page.

The source code is

<html>
  <head>
        <title>Input tutorial</title>
        <script language="javascript">
                function addNumbers()
                {
                        var val1 = parseInt(document.getElementById("value1").value);
                        var val2 = parseInt(document.getElementById("value2").value);
                        var ansD = document.getElementById("answer");
                        ansD.value = val1 + val2;
                }
        </script>
  </head>
  <body>
        value1 = <input type="text" id="value1" name="value1" value="1"/>
        value2 = <input type="text" id="value2" name="value2" value="2"/>
        <input type="button" name="Sumbit" value="Click here" onclick="javascript:addNumbers()"/>
        Answer = <input type="text" id="answer" name="answer" value=""/>
  </body>
</html>

save as addtwonumbers.html and then open in a web browser (e.g. FireFox)

78 thoughts on “Add two numbers”

  1. good code but try to generalize with multiplication,subtration,division with floation point numbers.

  2. great! but now something confusing is that if you just change the operator differently from what is defined to the “function” in the fifth line from above and “javascript” in the fourth line from below it will still work. what i mean is that change the operator in “ansD.value” into say multiplication and leave the “function” and “javascript” as “addNumbers” it will still work! can anybody tell me what does that mean!

  3. If you mean that you change the line..

    ansD.value = val1 + val2;

    to

    ansD.value = val1 * val2;

    then that is the functional aspects of the function itself and not the name of the function, the function name could be someMathsComputation because javascript does not really care what the name is as long as the functional aspects are in javascript code.

    Not sure if that is what you was meaning, or if that helps ?

  4. any way to limit the number of decimal points – my outputting number for example is 12.33445555 and i just want to display 12.33

    thanks

    paul

  5. Hi Paul,

    Yeah.. you could use

    number.toFixed(x) /// where x is the number of points you want to have.. in your case

    number.toFixed(2) should work :).

  6. hi santhosh,

    from memory you have to
    import java.text.DecimalFormat;

    and then create a decimal format variable
    double priceToBeFormatted = 1.302;
    DecimalFormat theFormatter = new DecimalFormat(“#0.00000”);
    out.println(theFormatter.format(priceToBeFormatted);

    HTH

  7. Input tutorial

    function addNumbers()
    {
    var val1 = parseInt(document.getElementById(“value1”).value);
    var val2 = parseInt(document.getElementById(“value2”).value);
    var ansD = document.getElementById(“answer”);
    ansD.value = val1 + val2;
    }

    value1 =

    value2 =

    Very Low
    Low
    Nominal
    Hi
    Very High

  8. I cannot see your source code, but if you are using drop down lists like HTML select tags then you use something like

    document.<formname>.<selectname>.options[document.<formname>.<selectname>.selectedIndex].value;

    HTH

  9. hi how r u

    how add three numbers

    for example this

    function calc()
    {
    var val1= parseInt (document.getElementById(parseInt (“1”)).value);
    var val2= parseInt (document.getElementById(parseInt (“2”)).value);
    var val3= parseInt (document.getElementById(parseInt (“3”)).value);
    var ansD = document.getElementById(“answer”);
    ansD.value = val1 val3 val2;
    }

    value1 =
    value2 =
    value3 =

    Answer =

    plz check my this code plz

  10. This should work

    <html>
      <head>
            <title>Input tutorial</title>
            <script language="javascript">
                    function addNumbers()
                    {
                            var val1 = parseInt(document.getElementById("value1").value);
                            var val2 = parseInt(document.getElementById("value2").value);
                            var val3 = parseInt(document.getElementById("value3").value);
                            var ansD = document.getElementById("answer");
                            ansD.value = val1 + val2 + val3;
                    }
            </script>
      </head>
      <body>
            value1 = <input type="text" id="value1" name="value1" value="1"/>
            value2 = <input type="text" id="value2" name="value2" value="2"/>
            value3 = <input type="text" id="value3" name="value3" value="4"/>
            <input type="button" name="Sumbit" value="Click here" onclick="javascript:addNumbers()"/>
            Answer = <input type="text" id="answer" name="answer" value=""/>
      </body>
    </html>

    Not sure if, but the ansD.value = val1 val3 val2; is missing a “+” and also if you are wanting to pass in integer values instead then

    var val1 = 3;

    hope that helps.

  11. hi thx but i don’t need this is val1 and val3 is textfield
    i mean is number field and value 2 is operator field in output

  12. Arh.. I think that I now know what you mean,

    <html>
      <head>
            <title>Input tutorial</title>
            <script language="javascript">
                    function addNumbers()
                    {
                            var val1 = parseInt(document.getElementById("value1").value);
                            var operator = document.getElementById("value2").value;
                            var val3 = parseInt(document.getElementById("value3").value);
                            var ansD = document.getElementById("answer");
                            eval("var ansForD = " + val1  + operator  + val3);
                            ansD.value = ansForD;
                    }
            </script>
      </head>
      <body>
            value1 = <input type="text" id="value1" name="value1" value="1"/>
            operator  = <input type="text" id="value2" name="value2" value="+"/>
            value3 = <input type="text" id="value3" name="value3" value="4"/>
            <input type="button" name="Sumbit" value="Click here" onclick="javascript:addNumbers()"/>
            Answer = <input type="text" id="answer" name="answer" value=""/>
      </body>
    </html>

    should do the trict 🙂

    I am using the eval method to eval(uate), which is basically like javascript code but you can insert textual data to create dynamic code as such.

  13. could use a

    <select><option value="+">+</option></select>

    instead of a

    <input>

    type

  14. k,, here is the source code for it to work 🙂

    <html>
      <head>
            <title>Input tutorial</title>
            <script language="javascript">
                    function addNumbers()
                    {
                            var val1 = parseInt(document.getElementById("value1").value);
                            var operator = document.getElementById("value2").value;
                            var val3 = parseInt(document.getElementById("value3").value);
                            var ansD = document.getElementById("answer");
                            eval("var ansForD = " + val1  + operator  + val3);
                            ansD.value = ansForD;
                    }
            </script>
      </head>
      <body>
            value1 = <input type="text" id="value1" name="value1" value="1"/>
            operator  = <select id="value2">
                    <option value="+">+</option>
                    <option value="/">/</option>
                    <option value="-">-</option>
                    <option value="*">*</option>
                    </select>
            value3 = <input type="text" id="value3" name="value3" value="4"/>
            <input type="button" name="Sumbit" value="Click here" onclick="javascript:addNumbers()"/>
            Answer = <input type="text" id="answer" name="answer" value=""/>
      </body>
    </html>
  15. to create a form in javascript, you just use the

    document.write(".... html code in here.... ");

    and write the html code for your form of choice within the document.write method.

  16. Hey guys am working on a similar code, but well the difference is that in my program the values keep getting added at every instant. So the value1 and value3 are first initialized to 0 and then on as and how they are changed the answer keeps changing dynamically without pressing the button. Need help guys seriously, I am having trouble in generating the answer dynamically without the button. Please HELP!

  17. No I dont :(. I am creating an application wherein you can enter values of the first two number and the answer automatically changes.
    example:(At start) the values would be 0
    + 0
    ______
    (So answer shown will also be) 0

    But as soon as I change the value of the number say make the first one as 1 the answer displayed should be “1”, likewise if I keep changing it the answer reflects the same. So it would be value1+ 0=value1,
    Similarly as and when I change value 3 the answer changes. And the change needs to happen very fast.
    I am designing a math aid for kids and this is meant to be a tool for addition. Need help with code guys.

  18. Input tutorial

    function addNumbers()
    {
    var val1 = parseInt(document.getElementById(“value1”).value);
    var operator = document.getElementById(“value2”).value;
    var val3 = parseInt(document.getElementById(“value3”).value);
    var ansD = document.getElementById(“answer”);
    eval(“var ansForD = ” + val1 + operator + val3);
    ansD.value = ansForD;
    }

    function displayManipulative()
    {
    var val1 = parseInt(document.getElementById(“value1”).value);

    var val3 = parseInt(document.getElementById(“value3”).value);
    var ansD = document.getElementById(“answer”);

    var manip1= document.getElementById(“manip1”);
    var manip2= document.getElementById(“manip2”);
    var manip3= document.getElementById(“manip3”);
    var manip4= document.getElementById(“manip4”);

    switch(val1)
    {
    case 0:
    break;
    case 1:
    manip1.value= desktop/banana.gif;
    break;
    case 2:
    manip1.value= desktop/banana.gif;
    manip2.value= desktop/banana.gif;
    break;
    case 3:
    manip1.value= desktop/banana.gif;
    manip2.value= desktop/banana.gif;
    manip3.value= desktop/banana.gif;
    break;
    }

    }

    noibo

    noibo
    huuh

    noibo
    huuh

    +
    /

    *

    This is the code. I ts based on whatever has been discussed here. So basically I am trying to get rid of the button. And at the same time trying to generate manipulative based on the value entered in the right text boxes. All the operations need to take place quickly.

    But firstly the button things aint working nor are the image manipulative getting generated :(…Please help!

  19. K Sounds like what you want to is to have onchange function that will alter the numbers accord-lying, nps.. can it be jquery ? or do you prefer to just use pure javascript ? do you want to use the contact me page ? so that I can email you instead and then place the finish article on here.

  20. ok well i dont mind whether its a javascript or jquery..but i jst need the addition to take place continuously…also need graphic that will represent the numbers and operations

  21. Hi Amrutha,

    I am using the onchange, to update the answer value once the values have been updated

    <html>
      <head>
            <title>Input tutorial</title>
            <script language="javascript">
                    function addNumbers()
                    {
                            var val1 = parseInt(document.getElementById("value1").value);
                            var operator = document.getElementById("value2").value;
                            var val3 = parseInt(document.getElementById("value3").value);
                            var ansD = document.getElementById("answer");
                            eval("var ansForD = " + val1  + operator  + val3);
                            ansD.value = ansForD;
                    }
            </script>
      </head>
      <body>
            value1 = <input type="text" id="value1" name="value1" value="1" onchange="javascript:addNumbers()"/>
            operator  = <select id="value2" onchange="javascript:addNumbers()">
                    <option value="+">+</option>
                    <option value="/">/</option>
                    <option value="-">-</option>
                    <option value="*">*</option>
                    </select>
            value3 = <input type="text" id="value3" name="value3" value="4" onchange="javascript:addNumbers()"/>
            <input type="button" name="Sumbit" value="Click here" onclick="javascript:addNumbers()"/>
            Answer = <input type="text" id="answer" name="answer" value=""/>
      </body>
    </html>

    HTH

  22. hi,

    This salomi here ,
    your script is good. working fine. it is flexible one.
    Thank you so much.
    all the best.

  23. hi ehm,
    i did some modification in that script u can refer this one.

    <html>
      <head>
            <title>Input tutorial</title>
            <script language="javascript">
                    function addNumbers()
                    { 
                            var val1 = parseInt(document.getElementById("value1").value);
                            var val2 = parseInt(document.getElementById("value2").value);
    						var val3 = parseInt(document.getElementById("value3").value);
    						var val4 = parseInt(document.getElementById("value4").value);
    						var val5 = parseInt(document.getElementById("value5").value);
                            var ansD = document.getElementById("grantTotalone");
                             ansD.value = val1 + val2+val3+val4+val5;
    						 document.getElementById("totaldiv1").innerHTML=ansD.value;
    						 addTotal();
                    }
     
    				function addnumberstwo()
    				{
    				       var val6 = parseInt(document.getElementById("value6").value);
    						var val7 = parseInt(document.getElementById("value7").value);
    						var ansD= document.getElementById("grantTotaltwo");
    						ansD.value = val6+ val7;
    						document.getElementById("totaldiv2").innerHTML=ansD.value;
    						addTotal();
    				}
    					function addnumbersthree()
    					{
    						   var val8 = parseInt(document.getElementById("value8").value);
    							var val9 = parseInt(document.getElementById("value9").value);
    							var ansD= document.getElementById("grantTotalthree");
    							ansD.value = val8+ val9;
    							document.getElementById("totaldiv3").innerHTML=ansD.value;
    							addTotal();
    					}
    			   function  addTotal()
    			   {
    			     var  totalOne=parseInt(document.getElementById("grantTotalone").value);
    				 var  totalTwo=parseInt(document.getElementById("grantTotaltwo").value);
    				 var  totalThree=parseInt(document.getElementById("grantTotalthree").value);
    				 var  ansD= document.getElementById("grantTotal");
    				 ansD.value = parseInt(totalOne+ totalTwo+totalThree);
    				 document.getElementById("finaltotaldiv").innerHTML=ansD.value;
    			   }
     
            </script>
      </head>
      <body>
            value1 = <input type="text" id="value1" name="value1" value="0" onkeyup="javascript:addNumbers()"/><br>
            value2 = <input type="text" id="value2" name="value2" value="0" onkeyup="javascript:addNumbers()"/><br>
    		value3 = <input type="text" id="value3" name="value3" value="0" onkeyup="javascript:addNumbers()"/><br>
    		value4 = <input type="text" id="value4" name="value4" value="0" onkeyup="javascript:addNumbers()"/><br>
    		value5 = <input type="text" id="value5" name="value5" value="0" onkeyup="javascript:addNumbers()"/><br>
    		<div id="totaldiv1"></div> 
    		<br><br>
    		First total=<input type="text" id="grantTotalone" name="grantTotalone" value="0" readonly="" onBlur="javascript:addTotal()" /><br><br><br>
    		value6 =  <input type="text" id="value6" name="value6" value="0" onkeyup="javascript:addnumberstwo()"/><br>
    		value7 =  <input type="text" id="value7" name="value7" value="0" onkeyup="javascript:addnumberstwo()"/><br>
    		<br><br>
    		<div id="totaldiv2"></div> 
    		Second total= <input type="text" id="grantTotaltwo" name="grantTotaltwo" value="0" readonly=""  onBlur="javascript:addTotal()" />
    		<br><br>
    		value8 =  <input type="text" id="value8" name="value8" value="0" onkeyup="javascript:addnumbersthree()"/><br><br>
    		value9 =  <input type="text" id="value9" name="value9" value="0" onkeyup="javascript:addnumbersthree()"/><br><br>
     
    		<div id="totaldiv3"></div> 
    		Third total =<input type="text" id="grantTotalthree" name="grantTotalthree" value="0" readonly="" onBlur="javascript:addTotal()"/>
    		<br><br><br><br>
    		<input type="text" id="grantTotal" name="grantTotal" value="" readonly=""/>		<br><br>
    		Grant total =<div id="finaltotaldiv"></div> 
     
     
     
      </body>
    </html>
  24. Not sure what you mean ? if you want to use four operators then just place them within the mathematical way.

    value1 = 4 + (2 / (4 * 3));

    javascript follows the same mathematical idea, so always best to place within brackets.

  25. Thanks for the simple code.
    The problem for me is what would be the code if I have a table with say 20 rows and in each row I want to do a separate addition between first field and second field of that row and get the result in the third field of that same row?

    is there anyway to do this without defining 20 separate functions for each row?

    thanks

  26. Kinder depends on how to you are sending those rows to the web page ? if is dynamical done with php/c# etc then you would just output the third column via the server code.

    If you are wanting to do it via javascript, then just need to reference the table colomns, and use a single function to add up the values. Using jquery may be easier with this sort of thing with its .parent() setup.

  27. Hi , I have just read ur post today .. in the similar way i tried to write the code on my own and could able to execute it however i wont get the final output wen i click on a button .. everythin seems to be fine.. kindly let me know d reason for its failure…
    the code is as follows …

    Add two numbers

    function add()
    {

    //document.write(“hello”);
    var val1 = parseInt(document.getElementById(‘value1’).value);
    var val2 = parseInt(document.getElementById(‘value2’).value);
    var sum = parseInt(document.getElementById(‘sum’));
    sum.value = val1 + val2;
    }

    value1 =
    value2 =

    sum =

  28. Hi Giridhar

    I would say it is because you are not outputing the result, e.g.

    document.write(val1+val2);

    or if you are if trying to update the web page document then

    var sum = document.getElementById(“sim”);
    sum.value = val1 + val2;

    HTH
    genux

Leave a Reply

Your email address will not be published. Required fields are marked *