Sum HTML Textbox Values using jQuery / JavaScript

sum-html-textbox-value-javascript
Here is a small code snippet to sum the values of all textboxes in a form in JavaScript using jQuery. I wrote it for some functionality and thought to share it with you all. The requirement is simple, whenever user modify the value of a textbox, the fresh sum should be calculated and displayed on the form. I used jQuery for this as it provides simple way of selecting elements and iterating through them.

Source Code

Following is the complete source code.

<html>
	<head>
		<title>Sum Html Textbox Values using jQuery/JavaScript</title>
		<style>
			body {
				font-family: sans-serif;
			}
			#summation {
				font-size: 18px;
				font-weight: bold;
				color:#174C68;
			}
			.txt {
				background-color: #FEFFB0;
				font-weight: bold;
				text-align: right;
			}
		</style>
		<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
	</head>
	<body>
<table width="300px" border="1" style="border-collapse:collapse;background-color:#E8DCFF">
	<tr>
		<td width="40px">1</td>
		<td>Butter</td>
		<td><input class="txt" type="text" name="txt"/></td>
	</tr>
	<tr>
		<td>2</td>
		<td>Cheese</td>
		<td><input class="txt" type="text" name="txt"/></td>
	</tr>
	<tr>
		<td>3</td>
		<td>Eggs</td>
		<td><input class="txt" type="text" name="txt"/></td>
	</tr>
	<tr>
		<td>4</td>
		<td>Milk</td>
		<td><input class="txt" type="text" name="txt"/></td>
	</tr>
	<tr>
		<td>5</td>
		<td>Bread</td>
		<td><input class="txt" type="text" name="txt"/></td>
	</tr>
	<tr>
		<td>6</td>
		<td>Soap</td>
		<td><input class="txt" type="text" name="txt"/></td>
	</tr>
	<tr id="summation">
		<td>&nbsp;</td>
		<td align="right">Sum :</td>
		<td align="center"><span id="sum">0</span></td>
	</tr>
</table>


<script>
	$(document).ready(function(){

		//iterate through each textboxes and add keyup
		//handler to trigger sum event
		$(".txt").each(function() {

			$(this).keyup(function(){
				calculateSum();
			});
		});

	});

	function calculateSum() {

		var sum = 0;
		//iterate through each textboxes and add the values
		$(".txt").each(function() {

			//add only if the value is number
			if(!isNaN(this.value) && this.value.length!=0) {
				sum += parseFloat(this.value);
			}

		});
		//.toFixed() method will roundoff the final sum to 2 decimal places
		$("#sum").html(sum.toFixed(2));
	}
</script>
</body>
</html>

Let us step by step see what above code is doing.

  1. First the $(document).ready() is called which gets triggered whenever the webpage is loaded.
  2. Inside $(document).ready(), we selected all textboxes by the class name “.txt” and iterate through each of them and added event handler on keydown event. Thus whenever keypress event will occur, the code will trigger calculateSum() function. Note that you may want to change the selector code that suits your html elements. In this case we selected textboxes based on class=”txt” as all textbox has this class.
  3. The keydown event triggers the function calculateSum(). In this function again we iterate through each textboxes and sum up the values in a variable sum. Note that we have checked whether the value is number before adding it to the sum.
  4. Finally we update the innerHTML property of span #sum using $("#sum").html(sum) code. You may want to display the sum in some textbox or some other place.

Online Demo


Click here to view online Demo



77 Comments

  • Dave 13 November, 2012, 19:08

    Viral,

    Code works great, thanks. Am trying to include it as part of an emailable form but cant get the sum value assigned. Any clues?

    • Dave 13 November, 2012, 19:10
      &lt;input class=&quot;txt&quot; type=&quot;text&quot; name=&quot;sum&quot; size=&quot;5&quot;&gt;&lt;font size=&quot;2&quot;&gt;Total : R&amp;nbsp; &lt;span id=&quot;sum&quot;&gt;0&lt;/span&gt;
    • Faraz 25 January, 2013, 12:21

      Hi SIr. This is Faraz from Q3.The code works great.:):):)

  • Sumit 13 December, 2012, 13:08

    How can we calculate the sum if their is a “comma” present in the textbox
    For example : $1,500.00

    I need to calculate the sum for these kind of values also .

    • kukuh 20 February, 2013, 9:11

      You need to use something like this:

      function addCommas(nStr)
      {
      nStr += ”;
      x = nStr.split(‘.’);
      x1 = x[0];
      x2 = x.length > 1 ? ‘.’ + x[1] : ”;
      var rgx = /(\d+)(\d{3})/;
      while (rgx.test(x1)) {
      x1 = x1.replace(rgx, ‘$1′ + ‘,’ + ‘$2′);
      }
      return x1 + x2;
      }

      function calculateSum() {

      var sum = 0;
      //iterate through each textboxes and add the values
      $(“.txt”).each(function() {

      //add only if the value is number
      if(!isNaN(this.value) && this.value.length!=0) {
      sum += parseFloat(this.value);
      }

      });
      //.toFixed() method will roundoff the final sum to 2 decimal places
      $(“#sum”).html(addCommas(sum.toFixed(2)));

      }

      http://stackoverflow.com/questions/6502333/add-thousands-separator-to-auto-sum

  • sitrarasu 13 February, 2013, 15:56

    it very useful for me. its works great…. thanks a lot………

  • madhuri 1 March, 2013, 12:30

    hi sir this code work very good but i need a code on submit button after giving the values could u plz give me the code for my project

    • SARAN 30 April, 2013, 18:19

      If u still need help
      Hey,U mean onSubmit of a form of a form?
      I didnt get ur complete requirement.Even then here is a suggestion,
      instead doing it onSubmit,Do it in onBlur of all text boxes that ll be useful for u.

  • Shalim 10 April, 2013, 12:00

    hello sir… your code is good….. but i want to display the total values in textbox…. can u help me pls??

    • SARAN 30 April, 2013, 18:17

      if u still need help,Here is the thing for it
      Create a text box with an id and do
      $(“#thatId).val(the value from CALCULATE SUM function);
      thats it

  • abhishek tiwari 23 April, 2013, 22:23

    Hello Viral Sir, Kem cho? mast blog che tamaro..mane bahu maja pade che……

Leave a Reply

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

Note

To post source code in comment, use [code language] [/code] tag, for example:

  • [code java] Java source code here [/code]
  • [code html] HTML here [/code]