Reputation: 87
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.
Upvotes: 0
Views: 462
Reputation: 3
to remove append element , you must use
delegate jquery event handler
$(document).delegate('#remCid', 'click', function(){
$(this).parents('p').remove();
});
Upvotes: 0
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
.
$(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:
$('.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