Change input number and sum form field values

Asked

Viewed 83 times

0

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

I need that when changing the content of an input (change), a given function captures all inputs of the form, takes the value of the attribute and multiplies by its value, after obtaining this result, sum all in a variable.

Input class: order_input_qnt

Sum result: order_total_price

In the 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));

  });
});
  • I could not interpret the question. Could you describe the operations step by step? Ex.: 1 - Sum the value of all fields, 2 - Multiply the result.... etc....

  • @Marcelovieira edited the post

  • Is that so? https://jsfiddle.net/w7ze1m68/3/

1 answer

1


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

You can use the this within the callback function of the each, that references 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: https://jsfiddle.net/w7ze1m68/2/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.