Dynamically calculate input with jquery

Asked

Viewed 694 times

1

Good afternoon, I have a dynamically input input code

function new_input() {
        $('<x>'
            + '<input class="cod" id="focus' + rscn +'" placeholder="Código" />'
            + '<input class="desc" placeholder="Descrição" />'
            + '<div class="div"></div>'
            + '<input class="quant" placeholder="Quantidade" />'
            + '<input class="val" placeholder="Valor" />'
            + '<span id="remove_item" class="remove cursor_pointer display_none">+</span>'
        + '</x>').prependTo(scntDiv);
        $('#focus' + rscn).focus();
        rscn++;
        contar_mais('itens_total');
        mask_money();
        return false; }

That by clicking new, inserts into the chosen div, all inputs that are programmed and activates maskmoney and updates the value in the item input

<div id='more_item_add' class='button cursor_pointer display_none'>Novo</div>
<div id='more_item'></div>
<input id='itens_total' class='itens_total' value='0' readonly='readonly' />

I am trying to make that by pressing the TAB or performing an onblur Event that in case is to take the cursor from the last input that is the value, it captures the amount in the previous input which is the Quant and multiplies by the value within it which is the val and updates the value of it by multiplying the quantity by the value inside it

that is to say

i type a quantity in the input Uant and hit the tab to go to the val and type the value inside it and hit the tab to go to the next input and in this event exit the input val, jquery read the quantity inside the Quantity multiply by the value inside the val and update the val with this new value by deleting the unit value and placing the value multiplied by the quantity

more or less what happens in this example http://jsfiddle.net/QBTN6/2/ but without the third input. grateful

Edit:

I found this code that I modified a little bit and I got almost there, that’s almost what this one does

<input class='teste_de_calculo resultado' />
<input class='teste_de_calculo calcula' />

<script>
$('input.teste_de_calculo.calcula').on('blur', function() {
  var v = 0;
  $('input.teste_de_calculo').each(function(i,e) {
    if ($(e).val()) {
      var i = $(e).val().replace(/\,/g,'.');
      if (isNaN(i)) { $(e).val(''); return; }
      v += parseFloat(i);
      $('input.teste_de_calculo.resultado').val(v.toFixed(2)); } }); });
</script>

Problem one of this code, it does not work if you change v += paseFloat(i); for v *= paseFloat(i); that is, it does not multiply, just sum

Problem two, only works on input 1 does not work on input 2

Probelma three, how to make it work on dynamic inputs

Edit

With the help of @Leo Caracciolo I managed to reach almost solution, the code then stayed in this format

function auto_calc_quant() {
    $('.val').blur(function() {
        $(this).val($(this).val().replace(',','.').replace(/[^0-9\.]/g,''));
        var a = Number(document.getElementById('teste_de_calculo quantidade').value);
        var b = Number(document.getElementById('teste_de_calculo resultado').value);
        if((a != '') && (b != '')) {
            var c = document.getElementById('teste_de_calculo resultado').value = parseFloat(a * b).toFixed(2).replace('.',','); } }); }

wish I could do the same using classes like in jquery $('teste_de_calculo resultado').value I know, I don’t really like Ids and run the calculation without having to exactly do Check, like, do it alone after the last change, example, I typed 3.90 ai in 0 it counts for about 3 seconds and changes the value without doing Check.

  • I don’t know if this would help, I tried to do it but I couldn’t understand https://www.scriptbrasil.com.br/forum/topic/62919-resultado-multiplica%C3%A7%C3%A3o-automatico/

  • v += paseFloat(i); will concatenate and not sum. You need to use v = v + paseFloat(i); instead.

  • Just change the keyup event to Blur, is there in response with the 2 events

1 answer

3


With keyup event

 $(document).ready(function() {
   $('.somente-numero').keyup(function (e) {
	$(this).val($(this).val().replace(/[^0-9\.]/g,''));
	  var v1 = Number(document.getElementById("teste_de_calculo resultado").value);
          var v2 = Number(document.getElementById("teste_de_calculo calcula").value);
            if ((v1 !="")&&(v2 !="")){
              var v3 = document.getElementById("teste_de_calculo calcula").value = parseFloat(v1 * v2).toFixed(2);
            }
   });
 });
<script src="http://code.jquery.com/jquery-1.8.3.min.js" type="text/javascript"></script>

<input class="somente-numero" id='teste_de_calculo resultado' />
<input class="somente-numero" id='teste_de_calculo calcula' />

With Blur event

 $(document).ready(function() {
   $('.somente-numero').blur(function (e) {
	$(this).val($(this).val().replace(/[^0-9\.]/g,''));
	  var v1 = Number(document.getElementById("teste_de_calculo resultado").value);
          var v2 = Number(document.getElementById("teste_de_calculo calcula").value);
            if ((v1 !="")&&(v2 !="")){
              var v3 = document.getElementById("teste_de_calculo calcula").value = parseFloat(v1 * v2).toFixed(2);
            }
   });
 });
<script src="http://code.jquery.com/jquery-1.8.3.min.js" type="text/javascript"></script>

<input class="somente-numero" id='teste_de_calculo resultado' />
<input class="somente-numero" id='teste_de_calculo calcula' />

Category: Events

  • then, in the case is multiplying, but in input 1, I would need to calculate only when in input 2, in the case not while typing but in Blur

  • Just change the keyup event to Blur, Enjoy :)

  • in fact, only change from keyup to Blur, but, continuing on the first, the total needs to appear on the second in the calculation test.

  • I edited the answer. The names of input ids lead to a misguided interpretation of what you want. Just change the variable v3 test de_calculus result by test_de_calculus calculates

  • is that I did it on purpose to make it work, because I could not do it the other way around, it was wrong, then I explained in the question that was to calculate in the second, not in the first, I will try to put this model of yours in mine to see if it will work, Valew

  • Modifying a little, it looked like $(Document). ready(Function() { $('.auto_calc'). Blur(Function(e) { $(this). val($(this).val().replace(',','.')); $(this). val($(this).val().replace(/[ 0-9.]/g,')); var v1 = Number(Document.getElementById('teste_de_calculus quantity').value); var v2 = Number(Document.getElementById('teste_de_calculus result').value); if ((v1 !=')&(v2 !=')) { var v3 = Document.getElementById('teste_de_calculus result'). value = parseFloat(v1 * v2). toFixed(2). replace('.',','); } }); }); </script>

  • now the problem, how to join this in dynamic input

  • Better ask another question, put the code in the question and what you intend! Here is getting confused.

Show 3 more comments

Browser other questions tagged

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