Add dynamic line values automatically

2

As the example below, I'm trying to sum the values of the Qtde Transferir lines, which are dynamically generated as the result of the database, subtract from the value entered in the Quantidade a Transferir field and display the difference in the% p>

I'vebuiltthecodebelow,usingsomeexamplesIfound,itaddedthedynamicrows,butfirstIneedtoenterthevaluesintherowsandfinallytheFaltatocalculatetheQuantidadeaTransferir:

$(document).ready(function(){$("#qtde_entrada").on('change', function() {
    if($(this).val().length > 0) {
     var total = 0;
     $('.input').each(function(){
       var valor = Number($(this).val());
       if (!isNaN(valor)) total += valor;
     });
     var final = $("#qtde_entrada").val() - total;
     $("#qtde_falta").val(final);
    }
    });
});

The inputs are set as follows:

Download and Missing Qty:

      <tr>
          <td colspan='2'>Quantidade a Transferir:
          <input type = "number" id="qtde_entrada" name = "qtde_entrada"  min="1" max="99999" style="width: 10em;"> -
          <b>Falta: <input type = "number" id="qtde_falta" name = "qtde_falta" class="resultado" style="width: 10em;" readonly></b></td>
      </tr>

Download Qty (dynamic):

HTML += "<td><input type = 'text' size = '5' name = 'qtde_trans[]' id = 'qtde_trans[]' class='input' ></td></tr>";

Any suggestions on how you could do to first enter the total amount to be transferred and as you type in the rows it is displaying in the default?

    
asked by anonymous 27.01.2017 / 13:52

2 answers

3

You can separate the calculation into a function:

function calc() {
    if($(this).val().length > 0) {
      var total = 0;
      $('.input').each(function(){
        var valor = Number($(this).val());
        if (!isNaN(valor)) total += valor;
      });
      var final = $("#qtde_entrada").val() - total;
      $("#qtde_falta").val(final);
    }
}

And use it in the change event of both #qtde_entrada and dynamic fields:

$('#qtde_entrada').on('change', calc);
$('table').on('change', '.input', calc);

Notice the second line of code above, on construction is different. Because fields are dynamic, you need to use something called delegation . This is necessary because when you listen to an event in Javascript, it associates the response function with the elements present in the DOM ; so if we have the following code:

'$('.input').on('change', calc);

The calc function will be associated with the change event of the .input elements present at the time of the call. This would not solve your problem, since these fields are dynamic and can be inserted into the page after the above code is executed.

When we use the construction:

$('table').on('change', '.input', calc);

The jQuery library will associate the change event with the table element, but will execute the calc function only when the change occurs in the .input elements. This is due to the event bubbling , which causes that when an event occurs on an element, it (the event) is propagated to the parent higher from the element where the event was started, or until the propagation is canceled (returning false or calling the stopPropagation method of the event).

As shown in the image below, the event started at element number 3 and propagated up to element number 1:

Inthisway,theeventisnolongerassociatedonlywithelementsthatexistedatthetimeofassociation.Thenewelementswillalsopropagatetheeventandthecalcfunctionwillbecalledcorrectly.

Seeitworking: link

    
27.01.2017 / 15:05
2

The code almost does what you want, but does not recalculate while typing on the lines. To do this simply add them to the change event.

$(document).ready(function()
{
    $("#qtde_falta").val("? - 0.0"); // Definimos um texto inicial
});
function alteracaoValores() // Quando houver alterações, não importando qual dos campos for (das linhas ou da qtd transferir)
{
    var total = 0.0;
    $('.somatorio').each(function() // Tanto para alteração na linha superior como nas editadas...
    {
        var valor = Number($(this).val());
            if (!isNaN(valor)) total += valor;
    }
    var quant_entr = parseFloat($("#qtde_entrada").val());
    if(!isNaN(quant_entr))
    {
        var final = quant_entr - total;
            $("#qtde_falta").val(final);
    }
    else
    $("#qtde_falta").val("? - " + total); // Colocar texto quando não tiver campo quantidade a transferir preenchido.
}

HTML:

<tr>
      <td colspan='2'>Quantidade a Transferir:
      <input type = "number" id="qtde_entrada" name = "qtde_entrada"  min="1" max="99999" style="width: 10em;" onchange='alteracaoValores();'> -
      <b>Falta: <input type = "number" id="qtde_falta" name = "qtde_falta" class="resultado" style="width: 10em;" readonly></b></td>
</tr>

Dynamically generated HTML:

HTML += "<td><input type = 'text' size = '5' name = 'qtde_trans[]' id = 'qtde_trans[]' class='input somatorio' onchange='alteracaoValores();' ></td></tr>";
    
27.01.2017 / 15:08