Sum HTML Textbox Values using jQuery / JavaScript
- By Viral Patel on July 21, 2009

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> </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.
- First the
$(document).ready()is called which gets triggered whenever the webpage is loaded. - 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 triggercalculateSum()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. - 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. - 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
Get our Articles via Email. Enter your email address.
Can I use it on my wesite?
Annegärd
Hi Annegärd, Feel free to use above code in your website
If you want, you can link to this tutorial from your site.
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).
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
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!
@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
Is it possible in a ASP.Net text box under a grid? If possible, how?
Can it be done with asp.net textbox control ? and sum into one more text box ?
Hi Viral,
Can it be done with asp.net textbox control ? and sum into one more text box ?
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.
HOW CAN RETRIVE TEXTBOX VALUE FROM FORM.IF TEXBOX IS CRATE IN A LOOP .
THIS IS MY PROBLEM PLEASE TELL ME SOON
OK
thanks for help…………..
this code is working well…………..
every one can use this code for addition……….
thanks for code. but …. how to input the result of sum to textfield?
Hi Nanang.. Just use
$("#sum").value(sum.toFixed(2));code for textbox whos id is “sum”. Hope that will work.thanks for the code. It really helps.
How can I make it add the values in an option box?
Hi
how would one add a vat column and multiply result by 6.7%
Thanks
Great work ??
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
@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.
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
Hi Batowiise – Try:
$(“#sum”).val(sum.toFixed(2));This will work.
WOW !!!! Its working like magic.
Thanks
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.
From Where should i get this src file
@Bhavik – Here is the source code – http://viralpatel.net/blogs/demo/sum-textbox-value-javascript.html. Just goto that page and save the source from browser.
Hey, sum did not work.
Hey. Could you tell me how it would work with multipling. My amounts are from the db
Love it,
this has saved me doing manual addition of a form with over 50 fields.
thanks!
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…
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
not support for subtract value if i add -10
it does not work for me. it does not add the values.
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…
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.
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
@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(); }could you tell me how to sum in textbox and show the result in the textbox without submit?
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.
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!
@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:
with this one:
Hope this works
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: $(
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
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) && 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) && 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)); }Hi Dilip, You using two definitions of
calculateSum()method. In this scenario, you can create two methodscalculateSum1()andcalculateSum2()method to tackle.txtand.txtttextboxes.thanks a lot
Thanks a lot for your help.
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.
ok. i fix it.thnx