1
votes

I have a form with fields like invoice Quantity, Unit Price and Sub total. I want to loop through and get sub total of each input field and finally get sum of sub total. How can I do that on JQuery? Thanks.

My code:

$(document).keyup(function(event) {
    var sub_total = 0;
     $("#items .targetfields").each(function() {
         var qty = parseInt($("#quantity").val());
         var rate = parseInt($("#rate").val());
         $(".subtotal").val(qty * rate);
     });
});
1
Please post the relevant code here and explain what you tried and what problem you are havingwirey00
I guess you could be doing wrong with the use of ids in your selectors. ids have to be unique in your whole html document, otherwise you might get unexpected results when querying them.Dennis
can you post the relevant HTML alsowirey00
$(document).keyup(function(event) { var sub_total = 0; $("#items .targetfields").each(function(){ var qty = parseInt($("#quantity").val()); var rate = parseInt($("#rate").val()); $(".subtotal").val(qty * rate); }); });user1554459
<tr> <td><input type="text" nam="quantity" id="quantity" /></td> <td><input type="text" nam="rate" id="rate" size="5" /></td> <td><input type="text" nam="sub_total" id="item_input" /></td> </tr> <tr> <td><input type="text" nam="quantity" id="quantity" /></td> <td><input type="text" nam="rate" id="rate" size="5" /></td> <td><input type="text" nam="sub_total" id="item_input" /></td> </tr>user1554459

1 Answers

3
votes

I fixed some of your html (never use duplicate ids)

<table id="items">
    <tr class="targetfields"> 
        <td><input type="text" name="quantity" class="quantity" /></td>
        <td><input type="text" name="rate" class="rate" size="5" /></td>
        <td><input type="text" name="sub_total" class="subtotal" /></td> 
    </tr> 
    <tr class="targetfields"> 
        <td><input type="text" name="quantity" class="quantity" /></td>
        <td><input type="text" name="rate" class="rate" size="5" /></td>
        <td><input type="text" name="sub_total" class="subtotal" /></td> 
    </tr> 
</table>

total: <span id="total"></span>
​

And here's the js

$(function() {

    $("#items").keyup(function(event) {
     var total = 0;
     $("#items .targetfields").each(function() {
         var qty = parseInt($(this).find(".quantity").val());
         var rate = parseInt($(this).find(".rate").val());
         var subtotal = qty * rate;
         $(this).find(".subtotal").val(subtotal);
         if(!isNaN(subtotal))
             total+=subtotal;
     });
     $("#total").html(total);
    });

})​

see it live here