How to use jQuery to dynamically add text field in the form

Asked

Viewed 1,721 times

2

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

Example: to register a new patch and inform that it has 5 ports in the form, so fill, then it is to display 5 new input fields for it to inform what each port will connect. I’ve tried some code but failed.

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!")
});

})

inserir a descrição da imagem aqui

Where he brings doors like NULL inserir a descrição da imagem aqui

  • 1

    Missing close one div before that </form>

  • What exactly do you need?

  • the new fields filled need to be saved in the bank along with the others. Like this, it is not saving in the bank. Type in number of doors I saved in the bank passing the name="patchpanel.numPorts" and to save the doors description was to be *name="ports.Description" but for some time you are not taking the values of the field

  • @Carlosdiego as you want the data entered?

  • strings that can catch the description of the equipment, I put numeral but in vdd will be names. In vdd all fields are as Strings.

  • Do you understand @EGDEV? Voce can help me with this question tbm: https://answall.com/questions/218979/comorposso-gerar-url-tempor%C3%A1ria-para-recuperar-password-no-framework-play/219290#219290

  • I’m sorry it took me so long to answer, because I was running out of time. From what I understand you’re not getting the data of the new fields added?

  • In relation to your other question create a password reset page, that page will receive a parameter in the url that can be information like date and time of password exchange request and the user id or email, this information would be encoded for example in Base64, the page would search with this code in the database which the user to make the password exchange, this code must have an expiration time, if the user does not access the example page in 3 hours will have to ask again the link for password recovery, only record in the bank the date and time of the

  • request later and only check the time difference between the date recorded in the database and the date received by the url parameter, if the difference time between the two dates/time is greater than 3 hours will not allow password exchange and the user will have to ask again password recovery.

  • @EGDEV was able to solve the problem of taking the values of the fields and saving them in the database. Obgdo for help

  • @EGDEV looks at another problem I’m having based on your help already. https://answall.com/questions/220166/guardar-valores-temporariamente-em-campos-de-texto-inputs

Show 6 more comments

2 answers

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>
<script src="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 doing a for and printing the amount that form passed in the parameter you can simply direct already return the input

  • It worked, obgdo. I had forgotten to reference the JS file

1


You can try it like 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>
<script src="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>

  • I implemented as you did but my text field does not appear. I will update the question with your implementation

  • me another question, I want to validate the new fields in my database as I did in other Forms <div class="form-group"> <label>Number of ports:</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> how to do with these new fields dianically?

  • I will update the question already with your implementation and my new question.

  • @Carlosdiego tries to update his question with its implementation.

  • Ready @EGDEV, updated

Browser other questions tagged

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