Sunday 5 July 2015

Sum up columns of a table Javascript

I have a simple table set up in which a user can insert values into the boxes and onkeydown it will sum up the column.


HTML: Code

    <table>
    <tr>
    <td><input type="text" onblur="calTotal(this, 'tot')" /></td>
    <td><input type="text" onblur="calTotal(this, 'tot1')" /></td>
    </tr>
    <tr>   
    <td><input type="text" onblur="calTotal(this, 'tot')" /></td>
    <td><input type="text" onblur="calTotal(this, 'tot1')" /></td>
    </tr>
    <tr>   
    <td><input type="text" onblur="calTotal(this, 'tot')" /></td>
    <td><input type="text" onblur="calTotal(this, 'tot1')" /></td>      
    </tr>
    <tr>   
    <td><input type="text" id="tot" /></td>
    <td><input id="tot1" type="text" /></td>
    </tr>  
    </table>


javascript: Code

    <script type="text/javascript">
    function calTotal(txtBox, totBox)
    {
        var totVal;
        try
        {
        totVal = document.getElementById(totBox).value;
        if(totVal!= null && totVal!='')
         {
           document.getElementById(totBox).value= eval(parseInt(document.getElementById(totBox).value) + parseInt(txtBox.value));  
         }
         else
         {
            document.getElementById(totBox).value= txtBox.value;          
         }
        }
        catch(e)
        {}
    }
    </script>

No comments:

Post a Comment