Auto Calculate Sum using JavaScript

This simple source code will help you how to Auto Calculate Sum using JavaScript. This program runs by the user to enter two numeric value in the TextBox then the sum will automatically show in the other TextBox.

Creating Markup

This simple HTML source code contains the form field with three TextBox as shown in the image below. Result Here's the source code of the image above.
  1. <div style="width:290px; height:250px; padding:15px; background:azure; border:2px solid blue;">
  2.  <h2 style="color:blue;">Auto Calculate Sum</h2>
  3.         <form>
  4.                 <input type="number" class="number" autofocus="autofocus" /> <br>
  5.                 <span style="color:blue; font-size:30px; font-weight:bold;"> + </span> <br>
  6.                 <input type="number" class="number" /> <br>
  7.                 <span style="color:blue; font-size:30px; font-weight:bold;"> = </span> <br>
  8.                 <input type="text" id="total" disabled />
  9.         </form>
  10. </div>

Script

Copy this simple script and paste below to your markup in the BODY tag of your page.
  1. <script>
  2.         $('.number').keyup(function() {
  3.      var sum = 0;
  4.     $('.number').each(function() {
  5.         sum += Number($(this).val());
  6.     });
  7.     $('#total').val(sum);
  8.      
  9. });
  10. </script>

Output


Originally the form will be, Result After enter the two numeric value in the TextBox. So, this would be the output. Result Hope that this tutorial will help you a lot. Share us your thoughts and comments below. Thank you so much for dropping by and reading this tutorial post. For more updates, don’t hesitate and feel free to visit this website more often and please share this with your friends or email me at [email protected]. Practice Coding. Thank you very much.

Add new comment