Reputation: 5724
I have a small issue. So i have a php
page whose content return
a button using ajax
such as shown below:
HTML part:
<a href="#" class="unit_register_button">
Register
</a>
jQuery part:
$('a.unit_register_button').click(function(e){
e.preventDefault();
alert('yaay');
});
Problem:
The button does not respond to the jQuery
.
I have tried copying the exact line of html
with the button to the page directly and works perfect when I click
.
What is the solution and why does the button not work when it is displayed using ajax
?
Upvotes: 1
Views: 67
Reputation: 1028
There is couple ways, one of them is by using on
function:
$(document).on('click', 'a.unit_register_button', function(e){
e.preventDefault();
alert('Alert message');
});
And another is with delegate
function:
$(document).delegate('a.unit_register_button', 'click', function(e){
e.preventDefault();
alert('Alert message');
});
Here jsfiddle with working examples.
Hope this helps.
Upvotes: 0
Reputation: 25527
you should use event delegation for that
$(document).on("click","a.unit_register_button",function(e){
e.preventDefault();
alert('yaay');
});
Event delegation allows you to attach a single event listener, to a parent element, that will fire for all children matching a selector, whether those children exist now or are added in the future.
Upvotes: 3