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

Get our Articles via Email. Enter your email address.

You may also like...

134 Comments

  1. Annegärd says:

    Can I use it on my wesite?

    Annegärd

  2. Viral Patel says:

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

  3. Russ Cam says:

    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 says:

      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

  4. 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 says:

      @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 :)

  5. Shimul says:

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

  6. Prabhu says:

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

  7. Prabhu says:

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

  8. uday says:

    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.

  9. MANOJ says:

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

  10. gaurav says:

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

  11. nanang says:

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

    • Viral Patel says:

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

      • T says:

        it not working

  12. thanks says:

    thanks for the code. It really helps.

  13. Atlante says:

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

  14. James Kelly says:

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

    Thanks
    Great work ??

  15. Batowiise says:

    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 says:

      @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.

  16. Batowiise says:

    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 says:

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

  17. Batowiise says:

    WOW !!!! Its working like magic.

    Thanks

  18. Batowiise says:

    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.

  19. Bhavik Dharaiya says:

    From Where should i get this src file

  20. ana says:

    Hey, sum did not work.

  21. Don says:

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

  22. Dave says:

    Love it,

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

    thanks!

  23. Mirko says:

    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…

  24. Angie says:

    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

  25. sunny says:

    not support for subtract value if i add -10

  26. ngungu says:

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

  27. newbee says:

    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…

  28. angela says:

    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.

  29. oliver says:

    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 says:

      @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 says:

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

  30. Connor says:

    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.

  31. martin says:

    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!

    • Viral Patel says:

      @Martin – This is because you might not have copied jQuery javascript file in your folder containing HTML. Well that’s not a problem. Just replace following line no. 19 in your HTML document:

      <script src="jquery-1.3.2.min.js"></script>
      

      with this one:

      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
      

      Hope this works :)

  32. Connor says:

    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: $(

  33. Bobi says:

    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

  34. Dilip says:

    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 says:

      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 says:

        thanks a lot

  35. Mohammed Sabbir says:

    Thanks a lot for your help.

  36. Mohammed Sabbir says:

    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 says:

      ok. i fix it.thnx

  37. Peterisgb says:

    Hi, i’ve used this code to make a calc of stuff on the site, its a online RPG
    I’ve used this code to do $X plus Gold plus turns and points, the sum at the bottem i want to place in a paypal link
    the code is

    What do i put in the amount field to make this work

  38. Lawrence says:

    Hi. Thanks for the tutorial. It works but Is it possible to send the results into another textbox on the same form That means making to an ? Been trying for some time but don’t seem to be able to make it work.

  39. Siva says:

    Hi,

    I follow your code. But i am Multiple rows of text box. Pls check my code, help me to solve program.

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
    </head>
    
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
        <script type="text/javascript">
     $(document).ready(function(){
    							 
    		for(i=1;i<=3;i++){
    //			for(j=1;j<=3;j++){
            //iterate through each textboxes and add keyup
            //handler to trigger sum event
            $(".txt" + i).each(function() {
    // alert($("input:text").length);
    // alert($('.txt'+ i).length);
                $(this).keyup(function(){
                    calculateSum();
                });
            });
    //			}
    		}
        });
     
        function calculateSum() {
     
            var sum = 0;
    		for(i=1;i<=3;i++){
    //			for(j=1;j<=3;j++){
            //iterate through each textboxes and add the values
            $(".txt" +i).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" + i).html(sum.toFixed(2));
    		}
        }
        
        </script>
    </head>
    <body>
        <?php 
    	$num = 1;
       print '<table width="300px" border="1" style="border-collapse:collapse;background-color:#E8DCFF">';
    	for($i=1;$i<=3;$i++){
    		   
      print '  <form id="form1">
        <div>';
        print '<tr>'; 
    		for($j=1;$j<=3;$j++){
    			print '<td>Component'.$j.'</td>
            			<td> <input class="txt'.$j.'" type="text" name="txt'.$i.$j.'" ID="txt'.$i.$j.'" /></td>';
    						$num++;
    					}
    			print '<td>Sum :</td>
    					<td> <span class="sum'.$i.'">0</span> </td>
    					</tr>';
    print '    </div>
        </form>';
    	}
        
    print '     </table> ';  
    	       ?> 
    
    </body>
    </html>
    
    • Andres Salazar says:

      did you solve your problem with the multiple rows? i have the same problem and haven’t solve it yet

  40. I was wondering if you could incorporate or tell me how to incorporate a button that clears all the values so you can start over. Please help me out. TY^^

  41. prince says:

    This is very good script.

  42. shipra says:

    Hiiiii Viral
    Actually i want to do subtract and multiplication…how i have to do… i tried but….

    • Viral Patel says:

      Check calculateSum() method. You have to modify this method and add your logic of multiplication or subtraction there.

  43. vikas sharma says:

    i m beginner of jquery so please tell me how can i perform multiple task like(add, subtract, multiply, divide etc)

  44. rr says:

    Thanks,please help me for substract logic…

    • rajesh says:

      it will work in mvc3?

  45. Nanda says:

    Superb and thanks a lot :)

  46. Asif Hussain Ansari says:

    this is the superb code,can you give me multiply coding as same as sum.thanks

  47. Jay Benfield says:

    This is exactly what I was looking for and was a big time-saver. Thank you for sharing the code.

  48. Andres Salazar says:

    Will this code work for multiple textbox?

    • Faizan Noor says:

      Yes its working for multiple input text boxes.

  49. Faizan Noor says:

    Thanks !!! That’s great. This jquery script helped me out a lot in implementing the numbers addition which are entered at runtime by users in input text box.

  50. What about for “1 1/4” and “2 R” aka user input.

  51. Dave says:

    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 says:
      &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 says:

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

  52. Sumit says:

    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 says:

      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

  53. sitrarasu says:

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

  54. madhuri says:

    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 says:

      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.

  55. Shalim says:

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

    • SARAN says:

      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

    • jack says:

      how can i write code for row and column calculation in a single program?

  56. abhishek tiwari says:

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

  57. jose says:

    Hi

    I am newbie in this matter and in fact I was looking for something like this. But…

    I have 1 value that comes from sql database (e.g. 25.00) that must multiply by any user quantity digit (e.g. 4) that gives a partial total of 100.00

    Then I have another (e.g. 10.00) times (e.g. 5) gives a partial total of 50.00

    I need to add automatically the two partial values without submit button to give me a grand total of 150.00.

    Using your code it adds all the values because are text, In another words gives me 25.00+4+100.00+10.00+5+50.00=194.00

    Any way to sort this problem out?

    Thank you in advance.

    Jose

  58. LET Corp says:

    Code works fine, but am not a fan of javascript……intead of “onKeyUp” i want the field to be processed on page load with defauld values inside the textboxes…

    anybody with idea will be well appreciated

    thanks

  59. siddhartha says:

    hi Viral awesome work…. My pleasure if i get guidance from your side, on a same source code i am not able to display output of sum in text box. Below is the code please check , I am so kind of you.

    Sum Html Textbox Values using jQuery/JavaScript

     
     

    Date:

    Customer Name:

    Customer Mob No

    Perpose

    Vechile Number:

    Vechile Type:

    Vechile Model:

     
     

    Product Code
    product Name
    Quantity

    Item Amount

     
    Sum :
    //0

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

    Total Amount
     

    S.tax (10%)
     

    Discount
     

    Paid Amount
     

     
     
     

     
     

  60. S B SHANKAR says:

    how to round off the value of the sum. say for ex 155.45 it should be rounded off to 155 and if the sum is 155.5 then it should be rounded off to 156

  61. Henry Jahja says:

    Thank you very much.

  62. Jackie says:

    Great code, but how to is display the sum value in TEXT field? sample code is appreciated.

    Thank you.

  63. Jackie says:

    I found the answer for multiplying too.

    function calculateSum() {
     
            var sum = 1;
            //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").val(sum.toFixed(0));
        }
    
  64. chandrasekhar says:

    I want same type of code for substraction.

  65. Krish says:

    Hi,
    this code works awesome But its not work when im use this code in Master page. What can i do?

  66. Abel says:

    Very helpful to me..
    Thanks alot……………………

  67. Abel says:

    Very helpful to me.
    Thank u…

  68. Jegger says:

    I have a input fields which is dynamically added using the appendTo. If I input a value on the input fields it calculates the sum of it, so it works fine but when I delete an input field it does not change the sum of all the fields. How can I make it right?So that when I delete some of the dynamic input fields it will update the value and sum it up to correct value. Any bright ideas?It would be a great help.

  69. wajid raza says:

    code is great but sir the result show in an other textbox also.

  70. jaswinder says:

    i wana show nan in result if anyone of the field is not number

  71. Bob Campbell says:

    It only took me 2 days until I stumbled upon your snippet for adding text elements. I create a dynamic hidden values each time a shopping cart dynamic div is added. I changed the getter (.each) and setter (.text) selectors to what I needed and away it went.

    Worked like a charm!

    Thank you so much. Your code was a life-saver that added to a really nice shopping cart project for my website.. Soon to be in action. LOL

    You code revised to my need:

    
    function calculateSum() {
     
     		var sum = 0;
    		//iterate through each hidden input value and total them
    		$(".hide-value").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
     		$("#cumulative-total").text(sum.toFixed(2));
    
     		}
    	
    	// this is a really nice function.. only took me 2 days to find it.
    	calculateSum();  // fire the function
    
    
    • pawan gehlot says:

      thanks

  72. Tubs says:

    Running total is reset when using with Gridview paging.

  73. Mario F says:

    I could not for the life of me get document.ready to work. I put similar code inside pageLoad function instead. Is it because pageLoad and document.ready clash?

  74. Dhaval Vaja says:

    Hello sir i need code that covert number into words using jquery.
    pls sir reply asap

  75. hammy says:

    i have to take two text box as inputs
    then make four buttons add,sub,mul & divide
    then print result in third text box
    how to include functions
    n java script

  76. Nancy Marie says:

    This code works very well. If I have three separate rows in a form, each with its own sum, however, I can’t seem to get it to work. For the first row, I use .txt3, and #sum3, for the second row I use .txt2 and #sum2 and for the third row I use .txt and #sum. And only the last row seems to work.

    Could you help me understand what I might be doing wrong.
    Thank you for your assistance and the great piece of code.

    • David says:

      an example of what you have would be helpful. make sure the name attribute is set correctly. class is just for applying css… and type is to create the text box

  77. AM says:

    How to show this sum value in textbox in jquery

  78. Nice Post!!
    Thanks For sharing it..

  79. T says:

    Sum Html Textbox Values using jQuery/JavaScript

    body {
    font-family: sans-serif;
    }
    #summation {
    font-size: 18px;
    font-weight: bold;
    color:#174C68;
    }
    .txt {
    background-color: #FEFFB0;
    font-weight: bold;
    text-align: right;
    }

    1
    Butter

    2
    Cheese

    3
    Eggs

    4
    Milk

    5
    Bread

    6
    Soap

     
    Sum :
    0

    $(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));
    }

    How to show total in textbox

  80. waseem says:

    i want to do substraction on this. Plz can any one help……………..

  81. sourav says:

    very nice……can any one help me result of total sum with discount

  82. pankaj says:

    reallyyyyyyyyyy help a lot..thanks…

  83. Jayesh says:

    Great work.

  84. chandrasekhar says:

    how to pass the total to a data field or hidden text field in the same form

  85. Dracula says:

    the code works great, thanks a lot.
    but i have question that reads ” how do i create a function that allows me to type in the text field and displays character by character what i’m typing on another on another form…….any idea would be greatly appreciated

  86. snehal kumar says:

    i want to take diffrent name of all textbox, then how can i do sum of all that???

  87. Nel says:

    ===============
    how to apply this good in my problem sir?
    —————————-

    $(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));
    }

    —————————

    please help me… tnx.

    • Nel says:

      this is my txt fied sir with different name

      *this is input field*
      *this is input field*

      *the result should be here*

  88. Nel says:

    input type = “text ” name = “av_valuel”

    input type = “text” name = “av_imp”

    input type = “text” name = “av_total”

  89. FEROZ says:

    NICE TUTOR VERY HELPFULL.UMWAAA

  90. priyanka says:

    how can we pass the sum value to the controller, i am using .Net MVC…

  91. santosh says:

    i want to do addition of two cell in horizantal. Plz can any one help……………..

  92. sandeepm says:

    i need value assign to textbox from javascript

  93. hashim nadhir says:

    what if i have several text box with different class name, eg txt1, txt2 and txt3. How will i put it and i need to sum all the text box.

  94. Rodrigo says:

    Great code. I made a modification to the class names and now it won’t sum anymore??

    $(document).ready(function(){$(“.flipflop”).each(function(){$(this).keyup(function(){calculateSum();});});});function calculateSum(){var sum=0;$(“.flipflop”).each(function(){if(!isNaN(this.value)&&this.value.length!=0){sum+=parseFloat(this.value);}});$(“#sum”).html(sum.toFixed(2));}

    • Rodrigo says:

      sorry

      $(document).ready(function(){$(“.flipflop”).each(function(){$(this).keyup(function(){calculateSum();});});});function calculateSum(){var sum=0;$(“.flipflop”).each(function(){if(!isNaN(this.value)&amp;&amp;this.value.length!=0){sum+=parseFloat(this.value);}});$(“#sum”).html(sum.toFixed(2));}

  95. Gurpreet says:

    Thanks for the post…You saved mah job…..thanku..stay blessed!!!!!!!!!

  96. Sukhbir says:

    hii m sukhbir
    want your help
    my problem is that i have to create a table like below Record of patient which is to be filled weekly
    Patient Name…………… Email [email protected]
    date Weight Kcal BMI AGE
    15/2 50.5 70.7 80.8 30
    22/2 51.2 65.7 80.3 29
    add button submit button
    when i click on add button a row should be add when submit it should to go to email [email protected]
    and next week when to update the old table with all record should be display
    and by clicking add (i can update table and submit on email with new updated weekly on mail)
    Plz mail the code if possible
    Thanks & Regard
    Sukhbir Singh

  97. RaviReddy says:

    how can i get that sum value into our servlet

  98. RaviReddy says:

    hello
    i wana that sum value into our servlet but it is not working how can i get can u give me rpy plzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz

  99. mahboob Khan says:

    i want to do total_amount paid_amount remain_amount

  100. khan says:

    how i can calculate total amount paid amount remain amount

  101. Scotty G says:

    How do I make this display the TOTAL in another TextBox, not in a table cell?
    Here is example:

    <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="jquery-1.3.2.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 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(){$(":text").each(function(){$(this).keyup(function(){calculateSum();});});});function calculateSum(){var sum=0;$(":text").each(function(){if(!isNaN(this.value)&&this.value.length!=0){sum+=parseFloat(this.value);}});$("#sum").html(sum.toFixed(2));}</script>
    	</body>
    </html>
    
    
  102. Viral your tutorial is very nice, i really like it. I also recently wrote the same tutorial but i also did subtraction and i also try to keep my tutorial as simple as possible, hope you like it. https://htmlcssphptutorial.wordpress.com/2015/07/10/jquery-sum-subtract-two-input-fields/

  103. indra says:

    thanks a lot for your tutorial,
    i’m very helped

  104. reza says:

    hi
    i want
    input textbox : type total number
    some text box : type number
    ….. : type number
    ———————————–
    Difference : total – sum()

    if when Difference is 0 do not allow type in the textbox .

  105. Siddique Khan says:

    Thanks for sharing

  106. dan says:

    How to add subtotal, tax and total

    subtotal
    +tax
    =total
    ?

  107. dan says:

    Solution for calculating taxes:


    var taxe1 = sum * (5/100);
    var taxe2 = sum * (6/100);
    var taxes = taxe1+taxe2;
    var total = taxe1+taxe2+sum;
    $("#sum").html(sum.toFixed(2));
    $("#taxe1").html(taxe1.toFixed(2));
    $("#taxe2").html(taxe2.toFixed(2));
    $("#taxes").html(taxes.toFixed(2));
    $("#total").html(total.toFixed(2));

    Display html:


    Montant avant taxes: 0.00
    + taxe1 5%: 0.00
    + taxe 2 6%: 0.00
    = taxes: 0.00
    = Total avec taxes: 0.00

    I still have to change type=text by type = checkbox but after testing, it does not work. Anyone know how?

Leave a Reply

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