How to remove DIV specifies with javascript?

Asked

Viewed 2,436 times

1

Hello I have a registration screen of academic information; I need that field can 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 'X' will always remove 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 delete:

function Removeacademico() {
    $('#academico div#academico1:this').fadeOut(700, function () {
        $('#academico div#academico1:this').remove();
    });}

2 answers

0

You can identify individually which parent element with the academic id 1 and which you remove 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(https://api.jquery.com/) to improve a little the structure of your code.

0


You’re cloning an element with idwhich will be repeated, and with that its function will always find the first element with the id wanted.

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

See that there are several elements with ids, including you put the same id="FormacaoAcademica" in all form elements (select and input), which makes your code incorrect and more complicated.

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

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

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

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>

<link rel="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>

<div class="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>

  • Thank you very much sam, helped very much was breaking my head with this, thanks also for the tips, I am very much Noob still in javascrip and I am involved in some projects that this difficult to study.

  • Hello, what developed helped a lot, but I had some problems with Jquery, as you used version 2.1.1, I changed in my program, but other functions did not work, would have some hint, I used version 1.3.2

  • Man, thank you very much, but I managed to solve it here; I believe it is not the best way, but for now it solves. $("#btdel_task"). live('click', Function() { var div = $(this). Closest('#academico1'); div.fadeOut(700, Function() { div.remove(); }); });

Browser other questions tagged

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