ARTICLE

Calculating the Sum inside a table using Jquery

Posted by Shinuraj Articles | ASP.NET MVC with C# February 23, 2011
Here is one sample code to sum the column values using jquery.
Reader Level:

Here is one sample code to sum the column values using jquery.
 
HTML:
 
<table width="300px" border="1" style="border-collapsecollapsebackground-color#E8DCFF">
        <tr>
            <td width="40px">1</td>
            <td>Number</td>
            <td><input class="txt" type="text" name="txt" /></td>
        </tr>
        <tr>
            <td>2</td>
            <td>Number</td>
            <td><input class="txt" type="text" name="txt" /></td>
        </tr>
        <tr>
            <td>3</td>
            <td>Number</td>
            <td><input class="txt" type="text" name="txt" /></td>
        </tr>
        <tr id="summation">
            <td  colspan ="2" align="right">
                Sum :
            </td>
            <td align="center"><span id="sum">0</span></td>
        </tr>
</table>
 
jQuery:
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js">
</script>
    <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);
                    $(this).css("background-color""#FEFFB0");
                }
                else if (this.value.length != 0){
                $(this).css("background-color""red");
               }
            });
            $("#sum").html(sum.toFixed(2));
        }
</script>
 
Download the working sample and give a try!!

Login to add your contents and source code to this article
Article Extensions
Contents added by vinay thanekar on Feb 05, 2013
Contents added by vinay thanekar on Feb 05, 2013
comments
COMMENT USING
PREMIUM SPONSORS
Over-C is a holistic consortium of communications and technology specialists. We build, deploy and market both business as well as consumer products and solutions.
Join a Chapter
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
Get Career Advice from Experts