How to use jQuery to dynamically add text field in form

2

I have a form where the client needs to inform the number of ports of the patch panel, and according to the value that it populate this field, new fields appear dynamically to add other relevant information.

Example: to register a new patch and inform that it has 5 ports in the form, as soon as it is filled, then eh to display 5 new input fields so that it tells what each port will connect. I've tried a few codes but have not been successful.

My HTML form

<div class="form-group">
            <label>Número de portas:</label> <input type="text"
                name="patchpanel.numPortas" class="form-control"
                value="${flash['patchpanel.numPortas'] ? flash['patchpanel.numPortas'] : p?.numPortas}">
            <span class="alert-danger">#{error 'patchpanel.numPortas' /}</span>
        </div>

        <div class="inputs">
            <label for="quantidade">Equipamento conectado:</label> <a href="javascript:void(0)" id="adicionarcampo"><img src="/public/images/plus.png"></a><br>
            <input type="text" name="portas.descricao[]" placeholder="Informe o equipamento contectado a porta" class="form-control"/>
        </div>

My jQuery:

var max_fields = 10;
var wrapper = $(".inputs");
var add_button = $("#adicionarcampo");

var x = 1;
$(document).ready(function(){
$(add_button).click(function(e) {
e.preventDefault();
var length = wrapper.find("input:text.textAdded").length;

if (x < max_fields) {
x++;
$(wrapper).append('<div><a href="#" class="remove_field">Remover</a><input type="text" name="portas.descricao['+ (length+1) +']"class="form-control" placeholder="Informe o equipamento contectado a porta" /></div>');
 }

 });


 $(wrapper).on("click", ".remove_field", function(e) {
 e.preventDefault();
 $(this).parent('div').remove();
 x--;
 });

 $("#alert-target").click(function () {
toastr["success"]("I was launched via jQuery!")
});

})

WhereitbehinddoorsasNULL

    
asked by anonymous 07.07.2017 / 23:04

2 answers

1

You can try this:

var max_fields = 10;
var wrapper = $(".inputs");
var add_button = $("#adicionarcampo");

var x = 1;
$(add_button).click(function(e) {
  e.preventDefault();
  var length = wrapper.find("input:text.textAdded").length;

  if (x < max_fields) {
    x++;
    $(wrapper).append('<div><input type="text" name="campo' + (length+1) + '"class="form-control" placeholder="Seu texto" /><a href="#" class="remove_field">Remover</a></div>');
  }

});


$(wrapper).on("click", ".remove_field", function(e) {
  e.preventDefault();
  $(this).parent('div').remove();
  x--;
})
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div class="container-fluid">
<!-- Informando Quantidade -->
<form id="formQuantidade"> 
  <label for="quantidade">Informe a quantidade</label>
  <div class="inputs">
    <input type="text" name="campo[]"  class="form-control" placeholder="Seu texto">
    <br>
  </div>
  <a href="javascript:void(0)" id="adicionarcampo" class="btn btn-sm btn-success">Adicionar Campo</a>
</form>
</div>
    
08.07.2017 / 15:59
1

You can try using the example below, I believe that's what you need

const $formDinamico = $("#formDinamico");
$formDinamico.hide();

$("#formQuantidade").submit(function(e){
  e.preventDefault();
  //limpa form dinamico antes criar novos inputs
  $formDinamico.empty();
  //pega quantidade
  let quantidade = $("#quantidade").val();
  //retornando a quantidade informada de inputs
  let inputsDinamico = criaInputs(quantidade);
  
  $formDinamico.append(inputsDinamico);
  $formDinamico.append(criaBotaoSubmit());
  $formDinamico.show();
  
})

//pegando valores do form dinamico
$formDinamico.on('submit',function(e){
   e.preventDefault();
    console.log($(this).serialize());
});

function criaInputs(quant){
  let html = '';
  for(let i = 1; i <= quant; i++){
    html += '<input type="number" class="form-control"    class="inputDinamico" name="valor'+i+'" placeholder="Inputs Dinamico">';
  }
  return html;
}

function criaBotaoSubmit(){
  let html = '<button type="submit" class="btn btn-sm btn-success">Enviar</button>'
  return html;
}
@import url(https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css);

.btn{
  margin-top: 5px;
  margin-bottom: 5px;
}

.inputDinamico{
  margin-bottom: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"> </script>

<div class="container-fluid">
  <!-- Informando Quantidade -->
  <form id="formQuantidade"> 
     <label for="quantidade">Informe a quantidade</label>
    <input id="quantidade" type="number" class="form-control"    name="quantidade">
    <button id="enviarQnt" type="submit" class="btn btn-sm btn-success">Enviar</button>
  </form>
  
  <!-- via jquery "imprime" a quantiade de inputs necessários -->
  <form id="formDinamico">
  
  </form>

</div>

In your case instead of making a for and print the amount that form passed in the parameter you can simply direct already return the input

    
08.07.2017 / 14:56