dojo
dojo

Reputation: 453

Get sum of the values from form fields with JS/jQuery

I have dynamic form like:

<form id="formaa">
<div class="row">
  <input type="text" name="item" class="item"></input>
  <input type="text" name="quant" class="quant"></input>
  <input type="text" name="price" class="price" onkeyup="update();"></input>
  <input type="text" name="sum" id="suma" size="10" disabled="disabled"/>
</div>
<div class="row">
  <input type="text" name="item" class="item"></input>
  <input type="text" name="quant" class="quant"></input>
  <input type="text" name="price" class="price" onkeyup="update();"></input>
  <input type="text" name="sum" id="suma" size="10" disabled="disabled"/>
</div>    
<!-- ... many more rows -->
<input type="text" disabled id="total" name="tot"></input>
</form>

What I'm trying to do is multiply item quantity and price and get total sum in sum field for each item seperately (not all items total sum).

What I have achiecved is this function, but it seems counting total sum of all items together not seperately and this working with first default field row, when I add new set of fields and fill them with information both, fields (and other later added) sum values become NaN..If I remove all added field sets and leave the first form fows set, number is working again.. What is the problem here?

<script type="text/javascript">
function update() {
  var total = 0;
  $("#formaa div.row").each(function(i,o){
    total += $(o).find(".quant").val() *
        $(o).find(".price").val();
         if(!isNaN(total) && total.length!=0) {
                sum += parseFloat(total);
            }
  });
  $("#formaa div.row #suma").val(total);
}
</script>

Upvotes: 1

Views: 3827

Answers (1)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382150

function update() {
  $("#formaa div.row").each(function(i,o){
     var total = $(o).find(".quant").val() * $(o).find(".price").val();
     if(!isNaN(total) && total.length!=0) {
         sum += parseFloat(total);
     }
     $(o).find('[name="sum"]').val(total);
  });
}

A few problems in your code :

  • never give the same id to more than one element. That's the reason why I defined the selector on the name
  • you weren't resetting the total, so it was the sum of all
  • I didn't fix that, but your operation before the float parsing is strange (it may depend on the content that I can't see)

Upvotes: 4

Related Questions