MrGrinst
MrGrinst

Reputation: 1000

Add/Remove Fields on Form

Hey I'm trying to make a form page with addable and removable fields. The "Add Field" button works fine, but the "Remove Field" won't work. Anybody know why?

HTML

<div id="email">
<div>Primary Email:
<input type="text" name="email" length="40" />
</div>
</div>
<a href="#" onclick="return false;" id="addField">Add New Field</a>

JQuery

$(document).ready(function () {
var i = 1;
$("#addField").click(function () {
var targetDiv = $(this).prev('div');
$('<div>Pretend this is a text box <a href="#" id="rem" >Remove Field</a></div>').appendTo(targetDiv);
i++;
});

$('#rem').click(function () {
$(this).closest('div').remove();
});

});

Thanks!

Upvotes: 0

Views: 357

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

Note: Id should be unique, so instead of using rem as id use it as a class

So change

$('<div>Pretend this is a text box <a href="#" id="rem" >Remove Field</a></div>').appendTo(targetDiv);

to

$('<div>Pretend this is a text box <a href="#" class="rem" >Remove Field</a></div>').appendTo(targetDiv);

Then since you are working with dynamically added controls use event delegation model with .on()

$(document).on('click','.rem', function () {
    $(this).closest('div').remove();
});

Demo: Fiddle

Upvotes: 2

Related Questions