How to create and remove div s with inputs dynamically with jquery

Asked

Viewed 2,185 times

5

I need to create and remove dynamically div´s for a form I have, already made using table, but now I was asked div´s. I tried to make an adaptation but I couldn’t, what I need is to create a button to insert the div´s and one to remove them if necessary.

My full 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 that 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’m not gonna post what I tried to do 'cause I honestly can’t use it.

  • I was watching this video class yesterday, I hope it helps you: https://www.youtube.com/watch?v=UKKR0sEMGE8&list=PLcHPNq67CaVnHwfOeK9-7n57aOV6orMSO

3 answers

7


I suggest you create a div for package both .row that you want to add. Why? Because it will make it feasible to add new .row. How are they loose in the middle of <form>, it would be too complicated to add the new.

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

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

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

var cloneform = $('#dadosbanco').html();
$(document).on('click','.remDiv, .addDiv', function(e){
   var thisClass = Array.from(e.target.classList);
   ~thisClass.indexOf('remDiv')
      ?
      ($('.remDiv').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>
<form id="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 btn btn-styles" />
      </div>
   </div>
</div>
<br />

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

<br />
MAIS DIVS E CONTEÚDO AQUI

</form>

NOTES

  • Added [] the names of the fields to be sent in array form.
  • In relation to id'fields, if not used, I suggest you remove them, because when creating a new line, the id'will repeat and this will give problem if you use. I suggest instead of id's, use classes.
  • Hello @216, thanks for the great help, but I made a mistake posting my question, I have several "Rows" and put only the one I would like to insert, when I click the insert is inserting but inserting my first Row with fields that have nothing to do with the ones I need, forgive me the failure.

  • 1

    @adventistapr No problem. I’ve seen the update of the answer. So you want to add, in this case, two . Row, that’s it?

  • Good afternoon @Fuckin' Oh, that’s right.

  • 1

    @adventistapr Updated. Abs!

  • Excellent, thank you very much.

  • Your code does not work when implementing the . btn and . btn-Styles classes next to the . remDev class for an input or button.

  • 1

    @Eliseub. Tidy code. In the question it was foreseen that the buttons had only 1 class (remDiv or addDiv). But I adjusted it in case there were other classes together.

  • 1

    Even more readable, thank you for that =)

Show 3 more comments

2

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

$("#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 form element, you can use remove

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

If you want to remove a specific element, I advise using an id in div.

$('#id_div').remove();

1

Us names of inputs were added brackets [] at the end for the values to be saved in an array.

The input ids are different example id="BancoAutorizado' + x + ' where x is incremented with each addition of Divs

var max_divs limits the number of the set of added Divs

The method append() - allows adding 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>
<script language="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);
?>

Browser other questions tagged

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