Change input number and sum form field values

0

I have a form with several inputs number, each input has an attribute called product_val that contains a value.

I need to change the contents of an input (change), a particular function captures all the inputs of the form, get the value of the attribute and multiply by its value, after obtaining this result, add them all into a variable. >

Input class: order_input_qnt

Result of the sum: order_total_price

No jsfiddle

jQuery(function ($)
{
 $('.order_input_qnt').on('change',function()
 {
  $(".order_total_price").html("...");

  var sum = 0;
  $(".order_input_qnt").each(function()
  {
     if ($(".order_input_qnt").val().length > 0) {
         var valor = parseFloat($(".order_input_qnt").attr("product_val")) * parseFloat($(".order_input_qnt").val());
         sum += valor;
     }
  });
  $(".order_total_price").html(sum.toFixed(2));

  });
});
    
asked by anonymous 02.01.2018 / 20:45

1 answer

1

The problem with your code is within each . In the callback function of each you are trying to get the result of each item to do the calculation, however when using $('.order_input_qnt').val() you are always picking up the value of the first item. Since .order_input_qnt represents a collection of elements and val() will return only the value of an element (in the case of the first).

You can use this within the callback function of each , which refers to the current item in the iteration, for example:

jQuery(function ($)
{
  $('.order_input_qnt').on('change',function()
  {
      $(".order_total_price").html("...");

      var sum = 0;
      $(".order_input_qnt").each(function()
      {
        var val = $(this).val()
         if (val.length > 0) {
             var valor = parseFloat($(this).attr("product_val")) * parseFloat(val);
             sum += valor;
         }
      });
      $(".order_total_price").html(sum.toFixed(2));

  });
});

JSFiddle: link

    
02.01.2018 / 21:14