Problem removing elements with jQuery

2

I'm trying to remove fields from a form that are within for . The problem is that only the first element of for is removed, the others do not work.

I think maybe you did something wrong in the function, I have no experience with jQuery. Here is the code below:

HTML:

<div id="dados">    
   @for($i=0; $i<3;$i++)
      <span>    
         <input type="text" name="op1">
         <a href="#" id="remover">Remover</a>
      </span>    
   @endfor    
</div>

JS:

$(document).ready(function(){
    $('#remover').click(function(){
       $(this).parents('span').remove();
       return false;
    });
)};
    
asked by anonymous 07.01.2016 / 12:11

3 answers

4

Your problem is exactly in the selector, which uses a unique identifier, use classes that will work.

Example:

var div = '<span><input type="text" name="op1"><a href="#" class="remover">Remover</a></span>';

var conteudo = $("#conteudo");

conteudo.append(div);
conteudo.append(div);
conteudo.append(div);

$(".remover").click(function() {
  $(this).parent('span').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script><divid="conteudo"></div>
    
07.01.2016 / 12:31
3

The problem is that you are using multiple IDs. Within the for loop you are using N times <a href="#" id="remover">Remover</a> with the same ID and this is HTML invalid.

You have to use classes, for example:

HTML

<a href="#" class="remover">Remover</a>

jQuery

$('.remover').click(function(){

Or use like this, without IDs:

$('#dados a').click(function(){

And then you can use .closest('span') , in both cases, since you only want to remove that block where there was a click.

    
07.01.2016 / 12:29
1

Do so, which should resolve. Follow the fiddler with this running.

$(document).ready(function(){

    $('.remover').bind('click',function(){  
      $(this).parent().remove();
    });

});
    
07.01.2016 / 12:21