How to remove specific DIV with javascript?

1

Hello, I have a database of academic information; I need this field to be duplicated and removed, but when I remove only the first DIV and deleted; I use the javascrip below, when the person clones the field appears the 'X' to delete, but if it duplicates more than once the last 'X' will delete the first field, no matter what 'X' always removes the first field.

HTML:

<div id="academico" class="tab-pane fade">
                            <div id="academico1">
                                <div class="col-xs-9">
                                    <label for="ex3">Formação</label>
                                    <input class="form-control input-sm" title="Digite o nome do curso" id="FormacaoAcademica" name="estudo[]" type="text" >
                                </div>

                                <div class="col-xs-3">
                                    <label for="ex3">Status</label>
                                    <select class="form-control input-sm" id="FormacaoAcademica" name="estudo[]" >
                                        <option selected disabled>Selecione</option>
                                        <option>Cursando</option>
                                        <option>Concluido</option>
                                    </select>
                                </div>
                                <div class="col-xs-9">
                                    <label for="ex3">Nível</label>
                                    <input class="form-control input-sm" title="Especifique se o curso trata-se de curso tecnico, graduação ou pos-graduação"  name="estudo[]" type="text" id="FormacaoAcademica">
                                </div>
                                <div class="col-xs-3">
                                    <label for="ex3">Ano de conclusão</label>
                                    <input class="form-control input-sm" title="Digite o Ano de Conclusão"  name="estudo[]" type="text" id="FormacaoAcademica">
                                </div>
                                <div class="col-xs-3" id="botoesacademico">
                                    <a class="hidden" href="javascript:void(0)" id="btnova_tarefa" onclick="Removeacademico()" title="Remover"><img src="imagens/rem.png"/></a>
                                </div>
                                <hr style="clear:both;">
                            </div>
                            <center><a class="inline"  href="javascript:void(0)" id="btnova_tarefa" onclick="Clonaacademico()" title="Adicionar"><img src="imagens/add.png"/></a></center>
                        </div>

javascrip to Clone:

function Clonaacademico() { $("#academico1").clone().fadeIn(700).insertBefore($("#academico1")).find('#FormacaoAcademica').val('');
    document.getElementById("btnova_tarefa").setAttribute("class", "inline");
    count = count + 1;}

Javascrip to exclude:

function Removeacademico() {
    $('#academico div#academico1:this').fadeOut(700, function () {
        $('#academico div#academico1:this').remove();
    });}
    
asked by anonymous 19.07.2018 / 18:27

2 answers

0

You are cloning an element with id s that will repeat itself, and with that your function will always find the first element with id searched.

  

Keep in mind that a id must be unique on the page. When cloning   elements, use class instead of id .

See that there are multiple elements with id s, including you put the same id="FormacaoAcademica" in all form elements ( select and input ), which leaves your code incorrect and more complicated. p>

I reformulated all the code (HTML and JavaScript) by removing the errors, and I only used a click event to get the clicks on the "Add" and "Remove" buttons, differentiating one from the other by the title attribute, , if the button you clicked has on title "Add", the element is cloned; if you have "Remove", the respective block will be removed.

I have dispensed the use of the functions Clonaacademico() and Removeacademico() because the .on("click"... event already controls the functions of the buttons, as explained in the previous paragraph.

I also removed the javascript:void(0) buttons and used preventDefault() . This method cancels the action of the links.

Other explanations you can see in the code:

// cria o evento "click" para capturar o clique nos botões
$(document).on("click", ".btnova_tarefa", function(e){
   
   e.preventDefault();
   
   var t = $(this).attr("title"); // seleciona o title do elemento
   
   if(t == "Adicionar"){
   
      var p = $(".academico:eq(0)"); // seleciona a primeira div
      var c = p.clone(); // clona a primeira div
   
      c
      .hide() // esconde inicialmente o clone para aplicar o fadeIn
      .insertBefore(p)
      .fadeIn(700)
      .find('select, input') // seleciona elementos select e input
      .val(''); // esvazia os elementos
   
      c
      .find('.hidden')
      .attr("class", "inline btnova_tarefa");

   }else if(t == "Remover"){

      var p = $(this)
      .closest(".academico"); // seleciona o elemento pai com a classe
      
      p
      .fadeOut(350, function(){
         p.remove();
      });

   }
});
.hidden{
   display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><linkrel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script><divclass="academico">
     <div class="col-xs-9">
         <label for="ex3"><strong>Formação</strong></label>
         <input class="form-control input-sm" title="Digite o nome do curso" name="estudo[]" type="text" >
     </div>

     <div class="col-xs-3">
         <label for="ex3">Status</label>
         <select class="form-control input-sm" name="estudo[]" >
             <option selected disabled>Selecione</option>
             <option>Cursando</option>
             <option>Concluido</option>
         </select>
     </div>
     <div class="col-xs-9">
         <label for="ex3">Nível</label>
         <input class="form-control input-sm" title="Especifique se o curso trata-se de curso tecnico, graduação ou pos-graduação"  name="estudo[]" type="text">
     </div>
     <div class="col-xs-3">
         <label for="ex3">Ano de conclusão</label>
         <input class="form-control input-sm" title="Digite o Ano de Conclusão"  name="estudo[]" type="text">
     </div>
     <div class="col-xs-3 botoesacademico">
         <a class="hidden" href="#" title="Remover"><img src="imagens/rem.png"/></a>
     </div>
     <hr style="clear:both;">
 </div>
 <center><a class="inline btnova_tarefa"  href="#" title="Adicionar"><img src="imagens/add.png"/></a></center>
    
19.07.2018 / 20:22
0

You can individually identify the parent element with the academic id1 and remove it with the following code.

$("#btn-remover").click((e) => {                //evento click do mouse
    e.preventDefault();                         //desativa a função de refresh do link
    $(e.target).parent("#academico1").remove(); //seleciona e remove apenas a div que teve o botão remover clicado.
});

You can take a look at the jquery documentation ( link ) to improve the structure of your code.

    
19.07.2018 / 19:34