jaredwins
jaredwins

Reputation: 87

Remove an HTML element with jQuery after appendTo()

I have a form with a drop down menu. When a user selects something out of the drop down, it adds this element using jQuery appendTo:

<p><input type="text" id="callid" name="callid" placeholder="Call ID" /><a href="#" id="remCid"><span class="glyphicon glyphicon-remove"></span></a></p>

My problem is, when the glyphicon "X" is clicked, the element is not removed.

However, what baffles me, is if the above code is statically coded in the form (not added from my dropdown jQuery menu), clicking the "X" removes the element.

fiddle

Upvotes: 0

Views: 462

Answers (2)

erkunt
erkunt

Reputation: 3

to remove append element , you must use

delegate jquery event handler 

$(document).delegate('#remCid', 'click', function(){

    $(this).parents('p').remove();

});

fiddle

Upvotes: 0

Josh Crozier
Josh Crozier

Reputation: 240878

It's because the element #remCid doesn't exist in the DOM when the event listener is attached.

You could use event delegation and attach the event handler to a common ancestor that exists at the time. In this case, document.

Updated Example

$(document).on('click', '#remCid', function() {
    $(this).parents('p').remove();
});

It doesn't need to be attached to the document object.

For instance, attaching it to .more-fields would also work:

Example Here

$('.more-fields').on('click', '#remCid', function () {
    $(this).parents('p').remove();
});

As an alternative to event delegation, you could also attach the event listener after the element is appended. This may lead to logical errors, though, since multiple event listeners may be attached.

Upvotes: 3

Related Questions