How to add new jquery inputs through a number of a text box, but add only those that are missing

Asked

Viewed 229 times

1

Good

I have the following code that adds inputs conforms the number of inserted in a text box, however if the form already has some text boxes I just want to add the difference, ie

start text box : 2

After the amendment: amended text box - 3

Right now as I have it’s adding 3 to what already exists,

Follow the code I have at the moment

$(document).ready(function() {
var $txtQuantidade = $('#txtQuantidade');
var $btnAdicionar = $('#btnAdicionar');
var $divForm = $('#divForm');

$btnAdicionar.on('click', function() {
    var qtde = $txtQuantidade.val();
    console.log(qtde);
    var html = '';

    for (var i = 0; i < qtde; i++) {
        html += '<div>';
        html += '<input type="date" id="txtData_' + i + '" name="data[]">';
        html += '<input type="time" id="txtHoraIni_' + i + '"   name="hinicio[]">'
        html += '<input type="time" id="txtHoraFim_' + i + '" name="hfim[]">';
        html += '<div>';
    }

    $divForm.append(html);
});
});

<script  src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="txtQuantidade" />
<input type="button" id="btnAdicionar" value="Adicionar" />
<div id="divForm"></div>

I’ll try to explain it better:

Let’s imagine that I have 2 in the text box, I can only appear two inputs, if I insert 3 can only show me 3 inputs and finally if I put back 2 could only show me 2 inputs deleting one

thank you

  • if you are interested, follow your code without jQuery: Jsfiddle

  • Thanks for the help, but that’s not quite it, what controls the number of inputs is the value of the text box, IE, if there are two even if I click it will only keep 2 text boxes, if I insert 3 will just add one more. and if I later write 2 he will only have two, I do not know if I understand :/

  • 1

    Okay, I’ve changed the code to what you want: Jsfiddle

  • ey, thank you very much, perfect

3 answers

2

In that case, my friend, you’ll have to change the logic of yours for.

You need the variable i has the value "static". That is, the variable i will always have the last value inserted. And the quantity will be summed the desired amount.

$btnAdicionar.on('click', function() {

    // Define o número atual ou 0
    var numero = $(this).data('numero') || 0;

    // Precisamos do parseInt para somar os valores

    var qtde = parseInt($txtQuantidade.val());

    for (var i = numero; i < qtde + numero; i++) {
        html += '<div>';
        html += '<input type="date" id="txtData_' + i + '" name="data[]">';
        html += '<input type="time" id="txtHoraIni_' + i + '"   name="hinicio[]">'
        html += '<input type="time" id="txtHoraFim_' + i + '" name="hfim[]">';
        html += '</div>';
    }

    $divForm.append(html);

    // O último numero gerado
    $(this).data('numero', i);
});

So the logic will be like this

var i = ultimo_numero_inserido

quantidade + ultimo_numero_inserido

Then we’d have something like:

user Asked to enter 10

for ( i = 0; i < 10; i++);

Then asked to insert 5 more

for ( i = 10; i < 15; i++);
  • missed only you increase the numero before updating it on dataset: $(this).data('numero', qtde + numero);

  • It’s true @Tobymosque. Actually the intention was to put the i and not the numero

  • 1

    always forget that the i is still available outside the for.

2


Follows an implementation that makes no use of string manipulation and maintains index integrity.

var txtQuantidade = document.getElementById("txtQuantidade");
var btnAdicionar = document.getElementById("btnAdicionar");
var divForm = document.getElementById("divForm");
var tmplLinha = document.getElementById("tmplLinha").content;

btnAdicionar.addEventListener("click", function () {
  var quantidade = {};
  quantidade.old = parseInt(divForm.dataset.qtd) || 0;
  quantidade.new = parseInt(txtQuantidade.value) || 0;

  //adicionar novas linhas
  if (quantidade.new > quantidade.old) {
    for (var indice = quantidade.old; indice < quantidade.new; indice++) {
      var linha = document.importNode(tmplLinha, true);
      var inputs = linha.querySelectorAll("input[id]");

      [].forEach.call(inputs, function (input){    
        input.id = input.id + indice;
      });
      divForm.appendChild(linha);
    }
  } 

  //remover linhas excedentes
  if (quantidade.new < quantidade.old) {
    var linhas = [].slice.call(divForm.children, quantidade.new);
    linhas.forEach(function (linha, indice) {
      divForm.removeChild(linha);    
    });
  }

  divForm.dataset.qtd = quantidade.new;
});
<input type="text" id="txtQuantidade" />
<input type="button" id="btnAdicionar" value="Adicionar" />
<div id="divForm" data-qtd="0">

</div>
<template id="tmplLinha">
  <div>
    <input type="date" id="txtData_" name="data[]">
    <input type="time" id="txtHoraIni_" name="hinicio[]">
    <input type="time" id="txtHoraFim_" name="hfim[]">
  </div>
</template>

1

Without making many modifications to your code, an alternative to do what you need is to look for the number of children that the #divForm has and subtracts the amount reported in txtQuantidade, in this way.

var qtde = $txtQuantidade.val() - $divForm.children().length;.

Will stay like this:

$(document).ready(function() {
  var $txtQuantidade = $('#txtQuantidade');
  var $btnAdicionar = $('#btnAdicionar');
  var $divForm = $('#divForm');

  $btnAdicionar.on('click', function() {
    var qtde;
    if($txtQuantidade.val() <= $divForm.children().length) {
      for(i = 0; i < $txtQuantidade.val(); i++) {
        $divForm.children().last().remove();
      }
    } else {
      qtde = $txtQuantidade.val() - $divForm.children().length;

      console.log(qtde);
      var html = '';

      for (var i = 0; i < qtde; i++) {
        html += '<div>';
        html += '<input type="date" id="txtData_' + i + '" name="data[]">';
        html += '<input type="time" id="txtHoraIni_' + i + '"   name="hinicio[]">'
        html += '<input type="time" id="txtHoraFim_' + i + '" name="hfim[]">';
        html += '</div>';
      }

      $divForm.append(html);
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<input type="text" id="txtQuantidade" />
<input type="button" id="btnAdicionar" value="Adicionar" />
<div id="divForm"></div>

  • this ta almost perfect, but needed that if I decrease the number also decrease the number of inputs :/

  • @Orangemechanical I changed as I said.

Browser other questions tagged

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