user1588241
user1588241

Reputation: 131

Adding event handler to newly created element

I'm trying to add new element to ordered list with link for it's removal:

$('#list ol').append('<li>' + label + ' <a href="#remove_'+id+'">[remove]</a></li>');

but this is not working:

$('a[href^="#remove"]').on('click', function(event){
    alert('Removing: '+$(this).attr('href').substr(8));
    event.preventDefault();
});

Any idea why?

Upvotes: 5

Views: 2448

Answers (2)

Elliot B.
Elliot B.

Reputation: 17661

Wrap up the new element in jQuery tags and apply the event handler at that time. This is a cleaner and more efficient approach than using somewhat complicated jQuery selectors to assign the event handler after the element has already been inserted into the DOM:

//this line will create your element in memory, but not insert it to the DOM
var newElmt = $('<li>' + label + ' <a href="#remove_'+id+'">[remove]</a></li>');

//you can apply jQuery style event handlers at this point
newElmt.on('click',function(e) {

    alert('Removing: '+$(this).attr('href').substr(8));
    event.preventDefault();
});

//insert the element as you were before
$('#list ol').append(newElmt);

Upvotes: 8

thecodeparadox
thecodeparadox

Reputation: 87073

$('#list').on('click', 'a[href^="#remove"]', function(event){
    alert('Removing: '+$(this).attr('href').substr(8));
    event.preventDefault();
});

As you're append the li dynamically, so you need delegate event handling using .on() as delegate handler.

Upvotes: 0

Related Questions