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?
If you inspect your console, you will see the dynamically created elements injected in your DOM. Now we can add event handlers. To attach event handlers to the dynamically created button, we need to select the button with a class of btn and add an event listener of click .
The most flexible way to set an event handler on an element is to use the EventTarget. addEventListener method. This approach allows multiple listeners to be assigned to an element, and for listeners to be removed if needed (using EventTarget. removeEventListener ).
We can pass an object as an argument to the addEventListener method and specify that the event is only handled once. This is achieved by passing the property once to the object. If we set once to true, the event will only be fired once.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With