you are adding the event click
to input.apagar
before creating the same.
then put the evento
to all the input.apagar
pertaining to #content
using the method $.on
.
Another detail, the $.parents
will fetch all relatives, so if in your HTML tree you have more than one span above the input.apagar
it will also be deleted, so use the method $.parent
, After all you only want the first span
.
$(document).ready(function(){
var add = $('.add');
var content= $('#content');
add.click(function(){
content.append('<div><span> <input type="text" name="nome" value="Cópia" /> <button class="apagar">Apagar </button></span></div>');
});
content.on("click", "button.apagar", function(event){
$(event.target).parent().parent().remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="content">
<div>
<button class="add">Adicionar outro campo</button>
</div>
<div>
<span>
<input type="text" name="nome" value="Original" />
<button class="apagar">Apagar </button>
</span>
</div>
</div>
here is an adaptation of the @Gabrielrodrigues solution
$(document).ready(function() {
var add = $(".add");
var content = $('#content');
var onApagarClick = function() {
$(this).parents('span').remove();
};
add.click(function() {
var novaLinha = $('<span> <input type="text" name="nome" value="Cópia"> <button class="apagar">Apagar </button></span> <br>');
$('.apagar', novaLinha).click(onApagarClick);
$('#content').append(novaLinha);
});
$('.apagar').click(onApagarClick);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="content">
<div>
<button class="add">Adicionar outro campo</button>
</div>
<div>
<span>
<input type="text" name="nome" value="Original" />
<button class="apagar">Apagar </button>
</span>
</div>
</div>
The problem is the scope, put the delete inside the add click that will work.
– Gabriel Rodrigues
Thanks, you helped me out
– Amanda Lima