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

1

Good

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

start text box: 2

After change: altered text box - 3

At this point, as I have, I am adding 3 to what already exists,

Follow the code I have right now

$(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><inputtype="text" id="txtQuantidade" />
<input type="button" id="btnAdicionar" value="Adicionar" />
<div id="divForm"></div>

I'll try to explain better:

Let's say I have 2 in the text box, I can only see two inputs, if I enter 3 then only I can show 3 inputs and finally if I put 2, I could only show 2 inputs by deleting a

Thank you

    
asked by anonymous 09.12.2015 / 13:45

3 answers

2

This is an implementation that does not make use of string manipulation and maintains the integrity of the indexes.

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>
    
09.12.2015 / 15:42
2

In this case, my friend, you will have to change the logic of your for .

You need the i variable to have the value "static". That is, the variable i will always have the last value entered. And the quantity will be added to the amount desired.

$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 look like this

var i = ultimo_numero_inserido

quantidade + ultimo_numero_inserido

Then we would have something like:

user Asked to enter 10

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

Then you asked to insert another 5

for ( i = 10; i < 15; i++);
    
09.12.2015 / 13:58
1

Without making too many changes to your code, an alternative to do what you need is to find the number of children that #divForm has and subtract the amount reported in txtQuantidade , in this way.

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

It will look 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><inputtype="text" id="txtQuantidade" />
<input type="button" id="btnAdicionar" value="Adicionar" />
<div id="divForm"></div>
    
09.12.2015 / 13:57