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.


	%MINIFYHTML6b92a93304eecad4d4f39b6756132da332%%MINIFYHTML6b92a93304eecad4d4f39b6756132da38%
	
1 Butter
2 Cheese
3 Eggs
4 Milk
5 Bread
6 Soap
  Sum : 0
%MINIFYHTML6b92a93304eecad4d4f39b6756132da39%

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



114 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
      <input class="txt" type="text" name="sum" size="5"><font size="2">Total : R  <span id="sum">0</span>
    • 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……

  • jose 27 May, 2013, 21:20

    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

  • LET Corp 2 June, 2013, 23:06

    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

  • siddhartha 12 June, 2013, 11:08

    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
     

     
     
     

     
     

  • S B SHANKAR 2 July, 2013, 11:08

    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

  • Henry Jahja 10 July, 2013, 10:45

    Thank you very much.

  • Jackie 16 July, 2013, 12:44

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

    Thank you.

  • Jackie 16 July, 2013, 13:14

    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) && this.value.length!=0) {
                    sum *= parseFloat(this.value);
                }
     
            });
            //.toFixed() method will roundoff the final sum to 2 decimal places
            $("#sum").val(sum.toFixed(0));
        }
    
  • chandrasekhar 13 August, 2013, 12:48

    I want same type of code for substraction.

  • Krish 22 August, 2013, 14:56

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

  • Abel 3 September, 2013, 10:54

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

  • Abel 3 September, 2013, 10:55

    Very helpful to me.
    Thank u…

  • Jegger 5 September, 2013, 20:59

    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.

  • wajid raza 12 September, 2013, 14:53

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

  • jaswinder 9 October, 2013, 15:55

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

  • Bob Campbell 12 October, 2013, 13:53

    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
    
    
  • Tubs 7 November, 2013, 2:17

    Running total is reset when using with Gridview paging.

  • Mario F 12 December, 2013, 4:24

    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?

  • Dhaval Vaja 13 December, 2013, 18:26

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

  • hammy 5 January, 2014, 0:11

    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

  • Nancy Marie 10 February, 2014, 19:45

    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 13 March, 2014, 1:33

      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

  • AM 15 February, 2014, 15:00

    How to show this sum value in textbox in jquery

  • Sandeep Bhadauriya 25 March, 2014, 14:30

    Nice Post!!
    Thanks For sharing it..

  • T 27 March, 2014, 7:56

    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

  • waseem 22 May, 2014, 13:30

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

  • sourav 20 June, 2014, 14:38

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

  • pankaj 15 July, 2014, 21:04

    reallyyyyyyyyyy help a lot..thanks…

  • Jayesh 27 July, 2014, 15:42

    Great work.

  • chandrasekhar 22 August, 2014, 18:26

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

  • Dracula 4 September, 2014, 18:40

    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

  • snehal kumar 11 September, 2014, 18:24

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

  • Nel 20 October, 2014, 11:26

    ===============
    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 20 October, 2014, 11:29

      this is my txt fied sir with different name

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

      *the result should be here*

  • Nel 20 October, 2014, 11:31

    input type = “text ” name = “av_valuel”

    input type = “text” name = “av_imp”

    input type = “text” name = “av_total”

  • FEROZ 30 October, 2014, 9:41

    NICE TUTOR VERY HELPFULL.UMWAAA

  • priyanka 31 October, 2014, 9:57

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

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]