h00j
h00j

Reputation: 306

Dynamically Remove Elements Jquery .click not Firing

I am writing a script to dynamically create and remove elements, adding the elements works fine. But the #removeText function is not firing, I assume something because it was created after the page had finished loading or something. How can I get the #removeText click function to work if it has been dynamically created?

var i = 0;

$('#addText').on('click', function() {
    var div = $("#addText").closest('div').attr('id');

    $("<p><input type=\"text\" id=\"text" + i + "\" placeholder=\"Type something…\"><a href=\"#\" id=\"removeText\">Remove</a></p>").appendTo('#' + div);
});

$('#removeText').on('click', function() {
    console.log(1);
});

Upvotes: 0

Views: 231

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191749

If #removeText does not exist in the DOM when you call $("#removeText").on, then nothing gets bound because there is nothing to bind to because it does not exist.

All is not lost. Use event delegation:

$(document).on('click', '#removeText', function () {

You should probably do the same with #addText as well. You can delegate to elements that already exist in the DOM too.

Upvotes: 3

Related Questions