Error incrementing value in inputs with same class?

Asked

Viewed 40 times

2

I have a function that creates a loop of inputs depending on the number of installments entered by the user and when inserting a value in the first one it increases by 1 each of the following inputs,so far so good, but if he has inserted 10 payments and from the fifth installment he has given a sequence of checks from another checkbook that is not sequential to the previous checkbook, need that when entering the check number he increments in +1 from this example input below:

Checkbook 1 starts on sheet 2034 and ends on sheet 2038

parcela 1: 2034
parcela 2: 2035
parcela 3: 2036
parcela 4: 2037
parcela 5: 2038

check checkbook 2 starting with sheet number 7332

parcela 6: 7332
parcela 7: 7333
parcela 8: 7334
parcela 9: 7335
parcela 10: 7336

But what is actually happening is by inserting a new value at position 5 it increments incorrectly, and Blur also interferes with the values even if it has not changed it. Which way to bypass is flawed, or should I change the whole structure?

$(document).on('blur', '.ncheque', function() {
  var chqs = $('.ncheque');
  var index = null;
  var partes = this.value.split('-');
  var valor = parseInt(partes[1] || partes[0]);
  indice = chqs.index(this);
  if (valor) {
    $('.ncheque').each(function(index) {
      if (index > indice) {
        $(this).val([partes[1] ? partes[0] : null, valor + index].filter(Boolean).join('-'));
      }
    });
  } else {
    $('.ncheque').val('');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="ncheque"><br>
<input type="text" class="ncheque"><br>
<input type="text" class="ncheque"><br>
<input type="text" class="ncheque"><br>
<input type="text" class="ncheque"><br>
<input type="text" class="ncheque"><br>
<input type="text" class="ncheque"><br>

  • That one split('-') would it be what? The value can have hyphenate?

1 answer

1


A simpler way to do this compared to your code. By changing the value of a input, only the following will be modified increasing +1 the value of input altered.

$(document).on('blur', '.ncheque', function() {
   var chqs = $('.ncheque');
   var qtd = chqs.length; // quantidade de inputs
   var indice = chqs.index(this); // pega o índice do input blur
   for(var x=indice; x<qtd; x++){
      chqs[x+1] ? chqs[x+1].value = parseInt(chqs[x].value)+1 : null; // incrementa os seguintes até o final
   }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="ncheque"><br>
<input type="text" class="ncheque"><br>
<input type="text" class="ncheque"><br>
<input type="text" class="ncheque"><br>
<input type="text" class="ncheque"><br>
<input type="text" class="ncheque"><br>
<input type="text" class="ncheque"><br>

  • Got even faster using this way, thank you.

Browser other questions tagged

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