Problem removing elements with jQuery

Asked

Viewed 658 times

2

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

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

THE 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>

THE JS:

$(document).ready(function(){
    $('#remover').click(function(){
       $(this).parents('span').remove();
       return false;
    });
)};
  • 1

    id is unique selector, if you want to create multiple items use an identifier as a class to do. you are only removing the first why click Voce uses this, removing only the span relative of the clicked item, and not all.

  • But I don’t want to remove all not, I want to remove only one. for will generate 3 elements. Each element will have a remove button. When you click the remove button I want to remove the corresponding field. The problem is that only the button in the first field works and the others do not.

  • It worked as I wanted to by changing the id for class! Thank you

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>
<div id="conteudo"></div>

3

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

You have to use classes, for example:

HTML

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

jQuery

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

Or use like this, no Ids:

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

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

1

Do it like this, it should fix it. Follows the Fiddler with that working.

$(document).ready(function(){

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

});
  • Didn’t solve it. If I take the span from within the parent all page content is removed.

  • look at the Fiddler I made for you

  • Thank you. But the problem was solved just by changing id for class

Browser other questions tagged

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