Ahmed Sa'eed
Ahmed Sa'eed

Reputation: 35

Removing a parent element on click using jQuery

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

Answers (2)

Anand Chandwani
Anand Chandwani

Reputation: 124

try using this

$(document).on('click','#removeMember', function() {
    $(this).parent().remove();
});

Upvotes: 1

ptvty
ptvty

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

Related Questions