Reputation: 35
I am having trouble creating a dynamic form where a user can add and remove a text field. The functionality to add an extra field works fine, but removing the field just cannot seem to work.
My html is:
<div class="formItem" id="members">
<label for="workgroup">Add Members:</label>
<br />
<a href="#" id="addMember">Add another member</a>
<p>
<input type="text" name="members[]" placeholder="Enter email" autocomplete="off" />
</p>
</div>
My JS:
$('#addMember').on('click', function() {
$('<p><input type="text" name="members[]" placeholder="Enter email" autocomplete="off" /><a href="#" id="removeMember">Remove</a></p>').appendTo('#members');
return false;
});
$('#removeMember').on('click', function() {
$(this).parent().remove();
});
Upvotes: 1
Views: 27
Reputation: 124
try using this
$(document).on('click','#removeMember', function() {
$(this).parent().remove();
});
Upvotes: 1
Reputation: 5664
You are adding the click listener before actually creating the element, use:
$('#members').on('click', '#removeMember', function() {
$(this).parent().remove();
});
see these examples http://api.jquery.com/on/#entry-examples
Upvotes: 3