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



48 Comments

  • Annegärd wrote on 25 August, 2009, 22:51

    Can I use it on my wesite?

    Annegärd

  • Viral Patel wrote on 26 August, 2009, 1:17

    Hi Annegärd, Feel free to use above code in your website :) If you want, you can link to this tutorial from your site.

  • Russ Cam wrote on 5 September, 2009, 15:58

    I would highly recommend using $(‘input.txt’) as the selector as opposed to only $(‘.txt’) as this will cause all element nodes within the DOM to be checked to see if they have the class name ‘.txt’. Secondly, there is no need to use each() on the wrapped set to iterate through and bind an event handler to each element- binding an event handler to the wrapped set will bind the event handler to each element within the wrapped set by default. Thirdly, rather than binding an anonymous function to the keyup event which is only executing calculateSum(), you can just bind calculateSum to the keyup event directly. So, the code becomes

    $(function() {
    $(‘input.txt’).keyup(calculateSum);
    } );

    Reducing the length of the scope chain all over and improving performance speed (although in reality for this demo, it’s doubtful that the performance difference will be noticeable).

    • Viral Patel wrote on 5 September, 2009, 19:04

      Hi Russ,
      Thanks for the update. I agree with your suggestion of using “input.txt” as selector rather than “.txt”. It definitely reduce the scope of selector there by improving performance of the code. I will make changes in above code :)

      Thanks

  • Bogdan Munteanu wrote on 9 February, 2010, 22:14

    Hi Patel,
    Excellent job, well done. I was interested to use it but I’ve found a bug easy to reproduce: just put these values in your demo and check the result: 1.22; 1.22; 1; 1; 1; 1. It shows 6.4399999999999995 instead of 6.44. Is there a way to fix that?
    Thanks!

    • Viral Patel wrote on 9 February, 2010, 22:44

      @Bogdan: Thanks for finding the bug in final sum calculation. I have added .toFixed() the code at line #86. .toFixed(2) method will round off the final sum at 2 decimal places.
      I have also fixed the demo.

      Thanks again :)

  • Shimul wrote on 8 March, 2010, 16:24

    Is it possible in a ASP.Net text box under a grid? If possible, how?

  • Prabhu wrote on 11 March, 2010, 6:51

    Can it be done with asp.net textbox control ? and sum into one more text box ?

  • Prabhu wrote on 11 March, 2010, 7:05

    Hi Viral,
    Can it be done with asp.net textbox control ? and sum into one more text box ?

  • uday wrote on 29 March, 2010, 22:08

    Hi everyone,

    I want to learn jquery from the basis with the java. so i dont know where & how to start and please help in this.

  • MANOJ wrote on 19 May, 2010, 6:51

    HOW CAN RETRIVE TEXTBOX VALUE FROM FORM.IF TEXBOX IS CRATE IN A LOOP .
    THIS IS MY PROBLEM PLEASE TELL ME SOON
    OK

  • gaurav wrote on 25 June, 2010, 16:03

    thanks for help…………..
    this code is working well…………..
    every one can use this code for addition……….

  • nanang wrote on 11 July, 2010, 22:26

    thanks for code. but …. how to input the result of sum to textfield?

    • Viral Patel wrote on 12 July, 2010, 3:03

      Hi Nanang.. Just use $("#sum").value(sum.toFixed(2)); code for textbox whos id is “sum”. Hope that will work.

  • thanks wrote on 4 November, 2010, 16:52

    thanks for the code. It really helps.

  • Atlante wrote on 9 November, 2010, 8:53

    How can I make it add the values in an option box?

  • James Kelly wrote on 29 November, 2010, 21:01

    Hi
    how would one add a vat column and multiply result by 6.7%

    Thanks
    Great work ??

  • Batowiise wrote on 22 December, 2010, 18:57

    Hi,
    I want to link the sum total value to appear in a text box. I have applied the following code; $(“#sum”).value(sum.toFixed(2)); and changed all textboxes ids to “sum”.

    It is not working as expected. Need your help

    Great peace of work!!!
    Thanks

    • Viral Patel wrote on 24 December, 2010, 22:03

      @Batowiise – You dont have to change the ids of all textboxes to “sum”. Just make the id for last textbox where you want to display sum “sum”. It should work.

  • Batowiise wrote on 27 December, 2010, 14:08

    Hi,

    I did change the text box id where the final total will be to “sum” and still did not work. I did apply the following code too as well:

    $(“#sum”).value(sum.toFixed(2));

    and not

    $(“#sum”).html(sum.toFixed(2));

    What next again?

    Thanks

    • Viral Patel wrote on 27 December, 2010, 14:15

      Hi Batowiise – Try:
      $(“#sum”).val(sum.toFixed(2));
      This will work.

  • Batowiise wrote on 27 December, 2010, 19:28

    WOW !!!! Its working like magic.

    Thanks

  • Batowiise wrote on 6 January, 2011, 22:10

    Hi,

    I now want to implement a complex form that has subtotals. I tried duplicating script in the body tag like these;

    $(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
    $(“#subtotal1″).val(sum.toFixed(2));
    }

    $(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
    $(“#subtotal2″).val(sum.toFixed(2));
    }

    The problem now is that when i input a value, the subtotal2 totals everything while subtotal1 is empty.

    What should i do?

    Regards.

  • Bhavik Dharaiya wrote on 9 March, 2011, 13:10

    From Where should i get this src file

  • ana wrote on 23 March, 2011, 19:10

    Hey, sum did not work.

  • Don wrote on 5 May, 2011, 18:00

    Hey. Could you tell me how it would work with multipling. My amounts are from the db

  • Dave wrote on 28 May, 2011, 21:56

    Love it,

    this has saved me doing manual addition of a form with over 50 fields.

    thanks!

  • Mirko wrote on 29 July, 2011, 15:02

    Hi, well done, hope it will work in my project. I’d like to ask you for a not necessary (but cool) visual feature. What do you think about giving a nice effect to the way sum number updates? I mean, something like a fade in each time it refreshes…

  • Angie wrote on 22 August, 2011, 8:31

    Thanks for great code. Works well for me but I need to put the value in the input.txt into a text box so I can submit it so a database.
    What would the code look like to do that for each txt box ?
    Sorry I am a newbie to all this.
    Thanks

  • sunny wrote on 6 September, 2011, 11:47

    not support for subtract value if i add -10

  • ngungu wrote on 16 September, 2011, 13:56

    it does not work for me. it does not add the values.

  • newbee wrote on 14 October, 2011, 5:54

    Hi!

    What if my textboxes has different classes because of the layout of design and different names, what should I change in code?and If the textbox 1 and textbox 2 the value is from the database and the sum will save to the database also.

    Thank you…

  • angela wrote on 4 November, 2011, 15:30

    i have created a textbox and a button using javascript. Now once the user type a word suppose ‘boy’ in the textbox it should display like letter ‘b’ from boy should be in one textbox ‘o’ should be in other textbox and finally ‘y’ should be in another. there will be total 4 textbox. one 4 boy, one 4 b, one 4 ‘o’ n one for ‘y’. How to do this??? need help. Thanks in advance.

  • oliver wrote on 25 November, 2011, 16:17

    hello..what if the text box es has value already how do i get the correct code of it.
    hope somebody would help me.

    thanks

    • Viral Patel wrote on 25 November, 2011, 18:19

      @Oliver – You can call method calculateSum() on load of your page if you need to calculate sum if your textboxes are pre populated.

      $(document).ready(function() {
              calculateSum();
      }
      
      • Rattana wrote on 5 December, 2011, 13:35

        could you tell me how to sum in textbox and show the result in the textbox without submit?

  • Connor wrote on 2 January, 2012, 5:08

    hello, the script is work but need help to get the sum value to appear in a text box,
    I already try all of the following:

    the textbox display: $(

    thanks.

  • martin wrote on 2 January, 2012, 23:24

    Hi I am new to coding as my background is graphic design and electronics. Sorry for being nieve but this is exactly what i need, i have copied the code and pasted it to a html doc the table shows up well but i cant get the maths to work? do I need to upload a script doc to my web space?

    Thanks, great work btw!

  • Connor wrote on 4 January, 2012, 21:03

    None of the following work out on firefox..jquery is latest
    inbox type textbox id sum name sum
    value $(“#sum”).val(sum.toFixed(2)); or
    $(“#sum”).html(sum.toFixed(2));

    textbox display: $(

  • Bobi wrote on 13 January, 2012, 18:45

    Hi, I’m want to add in textbox values from mysql and get total sum, but in text filed not load data from $var ? Help please.
    Thanks

  • Dilip wrote on 29 January, 2012, 14:54

    Hi Great script however how can i use two or more versions of the script on the same page. I tried the below code but doesn’t work can you please tell me how can i use more than two versions on same page by changing class and id’s on my input boxes and the code

    var $ = jQuery.noConflict();
        $(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) &amp;&amp; this.value.length!=0) {
                    sum += parseFloat(this.value);
                }
    
            });
            //.toFixed() method will roundoff the final sum to 2 decimal places
            $(".sum").html(sum.toFixed(2));
        }
    
    var $j = jQuery.noConflict();
    
        $j(document).ready(function(){
    
            //iterate through each textboxes and add keyup
            //handler to trigger sum event
            $j(".txtt") .each(function()
    		  {
    
                $j(this).keyup(function(){
                    calculateSum();
                });
            });
    
        });
    
        function calculateSum() {
    
            var sum = 0;
            //iterate through each textboxes and add the values
            $j(".txtt").each(function() {
    
                //add only if the value is number
                if(!isNaN(this.value) &amp;&amp; this.value.length!=0) {
                    sum += parseFloat(this.value);
                }
    
            });
            //.toFixed() method will roundoff the final sum to 2 decimal places
            $j(".teamb").html(sum.toFixed(2));
        }
    
    • Viral Patel wrote on 29 January, 2012, 22:09

      Hi Dilip, You using two definitions of calculateSum() method. In this scenario, you can create two methods calculateSum1() and calculateSum2() method to tackle .txt and .txtt textboxes.

      • Dilip wrote on 1 February, 2012, 15:05

        thanks a lot

  • Mohammed Sabbir wrote on 1 February, 2012, 9:26

    Thanks a lot for your help.

  • Mohammed Sabbir wrote on 1 February, 2012, 9:42

    this is for .html(sum.toFixed(2)); but i want to put addition data to another textbox.when i do so using .val to going mad on me.how can i fix it.

    • Mohammed Sabbir wrote on 1 February, 2012, 9:47

      ok. i fix it.thnx

Leave a Reply

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

*

Copyright © 2012 ViralPatel.net. All rights reserved.