add input values and subtract them if necessary

0

Good morning, I have the following script which adds the real-time values of 5 input, they all have the class input_values_provisionals and shows them in a span of id total_provisionals

The question is that if for example the sum goes to 20 at the time of typing any of them and human error in one of them was not a 5 if not a 3, to delete the 5 and put the sum should be 17 and not 20 since I would be really subtracting a 2

Well, it turns out that it continues adding without brake, it shows me 23

What I can think of is that I should first validate what value there is currently, I did it with:

valor_actual=$(this).val();

to then compare it with the new value entered and so add or subtract the difference, I tried to do it but it takes the written value because as the function is with the event "change" because it will actually take me the new value entered and not the one that was already, here the code without the line that I tried

$(document).ready(function() {
  //guardara el total
  var total = 0;

  //cuando haya un cambio en el input 
  $('.input_valores_provisionales').change(function() {

    //valido que sea un numero
    if (!isNaN($(this).val()))
    {

       //va acumulando el total
      total += Number($(this).val());

      //muestra el total en el span
      $("#total_provisionales").text("$"+total);
    }
    else
    {
      //Si no introduce numero genera alerta
      alert("Debe ingresar un valor numerico");
    }
  });
});
    
asked by Gabriel Uribe Gomez 05.04.2018 в 21:28
source

2 answers

1

Another option using Jquery

$(document).ready(function() {

  //cada vez que el usuario orpime una tacla
  $('input').keyup(function() {
    var total = 0;

    //recorremos los input para que haga la suma
    $("input").each(
      function() {
        if (Number($(this).val())) {
          total = total + Number($(this).val());
        }
      });
    $("#resultado").text(total);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text"><br>
<p>Total: <span id="resultado"> 0</span></p>
    
answered by 05.04.2018 / 23:36
source
1

Another option, I do not know why but I do not like to call functions from HTML, I prefer to add events using selectors.

In short, it is detecting that the input changes and adding all the values. That way you do not have to know if it's a sum or a subtraction.

I share my solution.

var _EVENT_LISTENERS  = 'keyup change';
var $inputs           = $('.inputs');
var $total_element    = $('#total');

// EVENT LISTENER
$inputs.on(_EVENT_LISTENERS, '.inputs_valors_privisionales', suma_valores);

// ADD ALL INPUT VALUES
function suma_valores() {
  var total         = 0,
    $inputs_valores = $('.inputs_valors_privisionales');

  Array.from($inputs_valores).forEach((el) => {
    total = Number($(el).val()) + Number(total);
  });

  $total_element.text(total);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="inputs">
        <input type="number" min="-999" max="999" class="inputs_valors_privisionales" value="0" />
        <input type="number" min="-999" max="999" class="inputs_valors_privisionales" value="0" />
        <input type="number" min="-999" max="999" class="inputs_valors_privisionales" value="0" />
        <input type="number" min="-999" max="999" class="inputs_valors_privisionales" value="0" />
        <input type="number" min="-999" max="999" class="inputs_valors_privisionales" value="0" />
    </div>
<h1>Total: <span id="total">0</span></h1>
    
answered by 05.04.2018 в 22:54