How to create and remove divs with inputs dynamically with jquery

4

I need to dynamically create and remove div´s for a form that I have, I already did using table, but now I was asked div´s . I tried to make an adaptation but I could not, what I need is to create a button to insert div´s and one to remove them if necessary.

My complete form is:

<section>
   <div class="container">
      <div class="container">
         <div class="row">
            <header class="text-center margin-top-20">
               <h4 align="center">Preencha os campos para gerar a impressão do termo</h4>
            </header>
            <br>                    
            <header class="text-center margin-top-20">
               <h4 align="center">Informações Autorizador</h4>
            </header>
            <br>                    
            <div class="col-sm-1"></div>
            <div class="col-sm-10">
               <form id="frmCadastro" class="sky-form clearfix" action="" method="post" target="_blank">
                  <div class="row">
                     <div class="col-md-4 col-sm-4">
                        <input type="text" name="NomeAutorizador" id="NomeAutorizador" value="" class="form-control required" tabindex="2" placeholder="Nome">
                        <i class="fancy-arrow"></i> 
                     </div>
                     <div class="col-md-4 col-sm-4">
                        <input type="text" name="NacAutorizador" id="NacAutorizador" value="" class="form-control required" tabindex="2" placeholder="Nacionalidade">
                        <i class="fancy-arrow"></i> 
                     </div>
                     <div class="col-md-4 col-sm-4">
                        <input type="text" name="ProfAutorizador" id="ProfAutorizador" value="" class="form-control required" tabindex="2" placeholder="Profisssão">
                        <i class="fancy-arrow"></i> 
                     </div>
                  </div>
                  <div class="row">
                     <div class="col-md-6 col-sm-6">
                        <input type="text" name="CPFAutorizador" id="CPFAutorizador" value="" class="form-control required" tabindex="2" placeholder="CPF">
                        <i class="fancy-arrow"></i> 
                     </div>
                     <div class="col-md-6 col-sm-6">
                        <input type="text" name="RGAutorizador" id="RGAutorizador" value="" class="form-control required" tabindex="2" placeholder="RG">
                        <i class="fancy-arrow"></i> 
                     </div>
                  </div>
                  <div class="row">
                     <div class="col-md-6 col-sm-6">
                        <input type="text" name="EndAutorizador" id="EndAutorizador" value="" class="form-control required" tabindex="2" placeholder="Endereço">
                        <i class="fancy-arrow"></i> 
                     </div>
                     <div class="col-md-4 col-sm-4">
                        <input type="text" name="CidadeAutorizador" id="CidadeAutorizador" value="" class="form-control required" tabindex="2" placeholder="Cidade">
                        <i class="fancy-arrow"></i> 
                     </div>
                     <div class="col-md-2 col-sm-2">
                        <input type="text" name="UFAutorizador" id="UFAutorizador" value="" class="form-control required" tabindex="2" placeholder="UF">
                        <i class="fancy-arrow"></i> 
                     </div>
                  </div>
                  <header class="text-center margin-top-20">
                     <h4 align="center">Informações Autorizado</h4>
                  </header>
                  <br/>                       
                  // ESSA ROW QUE PRECISO INSERIR 
                  <div class="row">
                     <div class="col-md-4 col-sm-4">
                        <input type="text" name="NomeAutorizado" id="NomeAutorizado" value="" class="form-control required" tabindex="2" placeholder="Nome">
                        <i class="fancy-arrow"></i> 
                     </div>
                     <div class="col-md-4 col-sm-4">
                        <input type="text" name="CPFAutorizado" id="CPFAutorizado" value="" class="form-control required" tabindex="2" placeholder="CPF">
                        <i class="fancy-arrow"></i> 
                     </div>
                     <div class="col-md-4 col-sm-4">
                        <input type="text" name="RGAutorizado" id="RGAutorizado" value="" class="form-control required" tabindex="2" placeholder="RG">
                        <i class="fancy-arrow"></i> 
                     </div>
                  </div>
                  <div class="row">
                     <div class="col-md-4 col-sm-4">
                        <input type="text" name="BancoAutorizado" id="BancoAutorizado" value="" class="form-control required" tabindex="2" placeholder="Banco">
                        <i class="fancy-arrow"></i> 
                     </div>
                     <div class="col-md-4 col-sm-4">
                        <input type="text" name="AgenciaAutorizado" id="AgenciaAutorizado" value="" class="form-control required" tabindex="2" placeholder="Agência">
                        <i class="fancy-arrow"></i> 
                     </div>
                     <div class="col-md-4 col-sm-4">
                        <input type="text" name="CCAutorizado" id="CCAutorizado" value="" class="form-control required" tabindex="2" placeholder="Conta Corrente">
                        <i class="fancy-arrow"></i> 
                     </div> 
                  </div>
                  // ESSA ROW QUE PRECISO INSERIR**

                  <header class="text-center margin-top-20">
                     <h4 align="center">Local</h4>
                  </header>
                  <br/>    
                  <div class="row">
                     <div class="form-group">
                        <div class="col-md-12 col-sm-12">
                           <select name="Unicoop" class="form-control pointer required" id="Unicoop">
                              <option value="0">Unicoop</option>
                              <?php foreach ($ResUnicoop as $Unicoop) { ?>
                              <option value="<?php echo $Unicoop->IdUnicoop ?>"><?php echo $Unicoop->Nome ?></option>
                              <?php } ?>
                           </select>
                           <i class="fancy-arrow"></i> 
                        </div>
                     </div>
                  </div>

               </form>

              <div class="row">
                 <div class="col-md-12">
                    <button class="btn btn-primary  pull-right btn-block">IMPRIMIR</button>
                 </div>
              </div>                                   


               <div id="msgBusca" style="padding: 10px;">
                  <!-- Mensagens --> 
               </div>
            </div>
            <div class="col-sm-1"></div>
         </div>
      </div>
   </div>
</section>

I have several rows in this form, but the one I need to insert the most is this one:

<div class="row">
 <div class="col-md-4 col-sm-4">
    <input type="text" name="BancoAutorizado" id="BancoAutorizado" value="" class="form-control required" tabindex="2" placeholder="Banco">
    <i class="fancy-arrow"></i> 
 </div>
 <div class="col-md-4 col-sm-4">
    <input type="text" name="AgenciaAutorizado" id="AgenciaAutorizado" value="" class="form-control required" tabindex="2" placeholder="Agência">
    <i class="fancy-arrow"></i> 
 </div>
 <div class="col-md-4 col-sm-4">
    <input type="text" name="CCAutorizado" id="CCAutorizado" value="" class="form-control required" tabindex="2" placeholder="Conta Corrente">
    <i class="fancy-arrow"></i> 
 </div>
</div>

My form has this ID:

<form id="frmCadastro" class="sky-form clearfix" action="" method="post" target="_blank">

I will not post what I tried to do because honestly it will not be of any use.

    
asked by anonymous 21.11.2017 / 20:42

3 answers

6

I suggest that you create a div to package the two .row that you want to add. Because? Because it will make feasible the addition of new .row . Since they are loose in the middle of <form> , it would be very complicated to add the new ones.

I created a div with id="dadosbanco" and put the .row inside it. This way we will have this div as a reference and the work becomes extremely simpler.

I created a Add button to add the new .row and a Remove button on each line to remove its line. I also put in the function a code that prevents all lines from being removed, leaving at least one.

See the example below that you should adapt to your Bootstrap:

cloneform = $('#dadosbanco').html();
$(document).on('click','.remDiv, .addDiv', function(e){
   thisClass = e.target.className;
   thisClass == 'remDiv' ?
   ($('.'+thisClass).length > 1 ?
   $(this).closest('.row').prev().add($(this).closest('.row')).remove() : 0) :
   $('#dadosbanco').append(cloneform);
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js"integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js"integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><formid="frmCadastro" class="sky-form clearfix" action="" method="post" target="_blank">

OUTRAS DIVS E CONTEÚDO AQUI

<div id="dadosbanco">
   <div class="row">
      <div class="col-md-3 col-sm-3">
         <input type="text" name="NomeAutorizado[]" id="NomeAutorizado" value="" class="form-control required" tabindex="2" placeholder="Nome">
         <i class="fancy-arrow"></i> 
      </div>
      <div class="col-md-3 col-sm-3">
         <input type="text" name="CPFAutorizado[]" id="CPFAutorizado" value="" class="form-control required" tabindex="2" placeholder="CPF">
         <i class="fancy-arrow"></i> 
      </div>
      <div class="col-md-3 col-sm-3">
         <input type="text" name="RGAutorizado[]" id="RGAutorizado" value="" class="form-control required" tabindex="2" placeholder="RG">
         <i class="fancy-arrow"></i> 
      </div>
   </div>
   <div class="row">
      <div class="col-md-3 col-sm-3">
         <input type="text" name="BancoAutorizado[]" id="BancoAutorizado" value="" class="form-control required" tabindex="2" placeholder="Banco">
         <i class="fancy-arrow"></i> 
      </div>
      <div class="col-md-3 col-sm-3">
         <input type="text" name="AgenciaAutorizado[]" id="AgenciaAutorizado" value="" class="form-control required" tabindex="2" placeholder="Agência">
         <i class="fancy-arrow"></i> 
      </div>
      <div class="col-md-3 col-sm-3">
         <input type="text" name="CCAutorizado[]" id="CCAutorizado" value="" class="form-control required" tabindex="2" placeholder="Conta Corrente">
         <i class="fancy-arrow"></i> 
      </div>
      <div class="col-md-3 col-sm-3">
         <input type="button" value="Remover" class="remDiv" />
      </div>
   </div>
</div>
<br />

<input type="button" value="Adicionar" class="addDiv" />

<br />
MAIS DIVS E CONTEÚDO AQUI

</form>

NOTES

  • Added [] to field names to be sent in array form.
  • Regarding the% s of the fields, if they are not to be used, I suggest you remove them, because when creating a new line, the id 's will repeat itself and this will cause a problem if it is to be used. I suggest that instead of id 's, use classes.
21.11.2017 / 22:04
2

To add code dynamically with jQuery, you can use the append method.

$("#frmCadastro").append('<div class="row"> ... </div>');

Or if you want to change the content, you can use the method html

$("#frmCadastro").html('<div class="row"> ... </div>');

To remove the last element from the form, you can use remove

$('#frmCadastro').children('div').last().remove();

If you want to remove a specific element, I recommend using an Id in the div.

$('#id_div').remove();
    
21.11.2017 / 21:38
1
  

In the% of inputs% brackets were added names at the end so that the values are saved in an array.

     

The ids of the inputs are different example [] where x is incremented with each addition of divs

     

var id="BancoAutorizado' + x + ' limits the number of added divs set

The max_divs method - allows you to add content (a selector, an HTML element, an HTML string, or a jQuery object) to the END of an HTML element.

HTML + Library + Script

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><scriptlanguage="javascript">
<!--
$(document).ready(function() {
    var max_divs      = 10; //maximo conjunto de divs
    var wrapper         = $(".row");
    var add_button      = $(".botao_add");

    var x = 1; //contador de inseridos
    $(add_button).click(function(e){ //on add input button click
        e.preventDefault();
        if(x < max_divs){ //max input box allowed
            x++; // incrementa contador
            $(wrapper).append('<div><div class="col-md-4 col-sm-4"><input type="text" name="BancoAutorizado[]" id="BancoAutorizado' + x + '" value="" class="form-control required" tabindex="2" placeholder="Banco"><i class="fancy-arrow"></i></div><div class="col-md-4 col-sm-4"><input type="text" name="AgenciaAutorizado[]" id="AgenciaAutorizado' + x + '" value="" class="form-control required" tabindex="2" placeholder="Agência"><i class="fancy-arrow"></i></div><div class="col-md-3 col-sm-3"><input type="text" name="CCAutorizado[]" id="CCAutorizado' + x + '" value="" class="form-control required" tabindex="2" placeholder="Conta Corrente"><i class="fancy-arrow"></i></div><a href="#" class="remove_field">Remove</a></div>'); //add input box
        }
    });

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

//-->
</script>

<form id="frmCadastro" class="sky-form clearfix" action="" method="post" target="_blank">
<div class="row">
    <button class="botao_add">Add Mais</button>
 <div class="col-md-4 col-sm-4">
    <input type="text" name="BancoAutorizado[]" id="BancoAutorizado1" value="" class="form-control required" tabindex="2" placeholder="Banco">
    <i class="fancy-arrow"></i> 
 </div>
 <div class="col-md-4 col-sm-4">
    <input type="text" name="AgenciaAutorizado[]" id="AgenciaAutorizado1" value="" class="form-control required" tabindex="2" placeholder="Agência">
    <i class="fancy-arrow"></i> 
 </div>
 <div class="col-md-4 col-sm-4">
    <input type="text" name="CCAutorizado[]" id="CCAutorizado1" value="" class="form-control required" tabindex="2" placeholder="Conta Corrente">
    <i class="fancy-arrow"></i> 
 </div>
</div>
<button type="submit">Enviar</button>
</form>

PHP

<?php
  $arrayBancos = $_POST['BancoAutorizado'];
  $arrayAgencias = $_POST['AgenciaAutorizado'];
  $arrayCCAutorizados = $_POST['CCAutorizado'];

  print_r($arrayBancos);
  print_r($arrayAgencias);
  print_r($arrayCCAutorizados);
?>
    
22.11.2017 / 00:44