Reputation: 43
I have a problem with Jquery .on() function and Handlebars template. I wroted Handlebars template and add him dynamically in document:
$('.services-wrapper').append(serviceTemplate({index : ++maxIndex}));
This template has a button:
<p>
<?= Html::buttonInput('Delete', [
'class' => 'btn btn-danger delete-service',
'id' => 'js-delete-service',
'data' => [
'index' => $index,
],
]) ?>
</p>
So I wroted click handler on this button:
$('.service').on('click', '.delete-service', function (e) {
alert('Clicked');
//$(this).parent().parent().remove();
});
When I add this template to document, click event doesn't fire. What is the problem?
Upvotes: 0
Views: 793
Reputation: 1381
$("body").on('click','.delete-service',function(){
alert('Clicked');
});
Try this
Upvotes: 0
Reputation: 2607
You try to attach the event handler to an element which doesn't exists in your DOM structure. Before adding on('click')
try to console log $('.service')
. You need to use event delegation: https://learn.jquery.com/events/event-delegation/
So in your case:
$( ".service-wrapper" ).on( "click", ".delete-service", function( event ) {
event.preventDefault();
alert('Clicked');
});
Upvotes: 1
Reputation: 74738
You might need a closest parent wrapper as:
$('.service-wrapper').on(...);
Upvotes: 1