Jquery sum and subtract based values on textbox
<p>1) I have <strong>3 text boxes</strong> if first text box is filled second is automatically updated from DB and added to fill third.</p>

<p>2) however if 3rd text box is chosen then second is automatically updated from DB,  subtract 3rd and second to fill 1st text box. </p>

<p></p>

<pre><code>    &lt;td&gt;Sending Amount&lt;/td&gt;
    &lt;td&gt;&lt;input class="txt" type="text" name="txt" id = "sending"/&gt;&lt;/td&gt;


    &lt;td&gt;Charge&lt;/td&gt;
    &lt;td&gt;&lt;input class="txt" type="text" name="txt" id = "charge"/&gt;&lt;/td&gt;


    &lt;td&gt;Total Amount&lt;/td&gt;
    &lt;td&gt;&lt;input class="txt" type="text" name="txt" id = "totalAmount"/&gt;&lt;/td&gt;
&lt;/tr&gt;
</code></pre>

<p>
 </p>

<pre><code>    $(function () {
        var sending = $('input:text[id$=sending]').keyup(foo);
        var charge = $('input:text[id$=charge]').keyup(foo);            
        var totalAmount = $('input:text[id$=totalAmount]').keyup(foo);   

     function foo() {

            var value1 = sending.val();
            var value2 = charge.val();               
            var sum = add(value1, value2);
            $('input:text[id$=totalAmount]').val(sum);
    var sub = sub(value1, value2);
            $('input:text[id$=sending]').val(sub);
        }

        function add() {

            var sum = 0;
            for (var i = 0, j = arguments.length; i &lt; j; i++) {
                if (IsNumeric(arguments[i])) {
                    sum += parseFloat(arguments[i]);
                }
            }
            return sum;
        }

  function sub() 
         {
            var sub= 0;
            ***//need to create subtract function***
            }
            return sub;
        }

        function IsNumeric(input) {
            return (input - 0) == input &amp;&amp; input.length &gt; 0;
        }
    });
&lt;/script&gt;
</code></pre>

<p><strong>addition is working fine subtraction is not displaying correct value.</strong> </p>

<p>Tried below script, I think it does add and subtract .</p>

<pre><code>  &lt;script type="text/javascript"&gt;
   $(function () {
    var sending = $('input:text[id$=sending]').keyup(foo);
    var charge = $('input:text[id$=charge]').keyup(foo);            
    var totalAmount = $('input:text[id$=totalAmount]').keyup(foo);   
 function foo() {
        var value1 = sending.val();
        var value2 = charge.val();   

        if(IsNumeric(value2)){
        if(IsNumeric(value1)){
        var value3 = parseFloat(value1) + parseFloat(value2);
        $('input:text[id$=totalAmount]').val(value3);
        }}

        value3 = totalAmount.val();
        if(IsNumeric(value3)){
        if(IsNumeric(value2)){
        value1 = parseFloat(value3) - parseFloat(value2);
        $('input:text[id$=sending]').val(value1);
        }}
    }
    function IsNumeric(input) {
        return (input - 0) == input &amp;&amp; input.length &gt; 0;
    }
});
</code></pre>

<p></p>
