In this jQuery program, I am going to share the addition of two numbers using jQuery. This is a very easy and simple program written in jQuery to calculate any two numbers.
Create an index.html file and include the jQuery file before head tag closed.
1 2 | <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" type='text/javascript'></script> |
Copy paste below jQuery code inside the head tag.
1 2 3 4 5 6 7 8 9 | $(document).ready(function(){ $("#calculate").click(function () { var num1 = $("#num1").val(); var num2 = $("#num2").val(); var answer = parseInt(num1) + parseInt(num2); alert(answer); $("#answer").val(answer); }); }); |
Now copy the below HTML code and add to the index.html file inside the body tag.
1 2 3 4 | <input type="number" id="num1" class="form-control" placeholder="0"> <input type="number" id="num2" class="form-control" placeholder="0"> <input type="number" id="answer" class="form-control" placeholder="0" readonly> <button id="calculate" type="button">calculate</button> |
Now open the index.html page in your browser and execute the program to see the output. Below is the complet code this program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | <html> <head> <title>Addition of Two Numbers Using jQuery</title> <!-- include jquery file --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" type='text/javascript'></script> <script language="javascript"> $(document).ready(function(){ $("#calculate").click(function () { var num1 = $("#num1").val(); var num2 = $("#num2").val(); var answer = parseInt(num1) + parseInt(num2); alert(answer); $("#answer").val(answer); }); }); </script> </head> <body> <input type="number" id="num1" class="form-control" placeholder="0"> <input type="number" id="num2" class="form-control" placeholder="0"> <input type="number" id="answer" class="form-control" placeholder="0" readonly> <button id="calculate" type="button">calculate</button> </body> </html> |
See DEMO here,
See the live demo of above program by clicking on below Try it Yourself button.
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.
Article Tags: CSS, HTML 5, Javasrcipt, Jquery, Tip and tricks