Reputation: 1392
I am designing webpage using jquery and php. My page has side menu, and clicking one of the option it send a request to server to read some information from file and it will create a form out of it, with submit and other button edit(in case anybody wants to change the information in that form) and send this html back to client. I am able to do this successfully. But when I click on the edit button it actually not calling the click handler I registered for the all the buttons.
$('button').click(function(){
alert("click event");
});
I included this in the
jQuery(document).ready(function() {
But because all the jquery/js code in ready() and it gets executed at the page load time, its not able to find these buttons in form because its something which i get from server after loading and replacing it to existing 'div' and hence its not able to invoke the event handler. If I define click handler for the parent div of this form, it receives the click event if I click 'edit' button because that 'div' was present when initial page got loaded. I might not be doing it correctly, may be getting the whole form from server is not a good idea, if you have to do some operation on the form at client side. But is it doable? if yes then whats the possible way out?. Thanks!
Upvotes: 1
Views: 2693
Reputation: 207900
Your event isn't firing because you define it prior to the element existing on the page. Using the .on() method should fix this. Something along the lines of:
$('body').on('click','button', function(){
alert("click event");
});
should work.
Upvotes: 3
Reputation: 6619
If I understand you correctly you adding the buttons dynamic to the form. You should try to use jQuery.on()
insteed, see http://api.jquery.com/on/
And in your example this might work for you
$("body").on("button","click", function(event){
alert("Hello world");
});
Upvotes: 3
Reputation: 11385
Use on (jQuery 1.7 and up). Previously was delegate (1.4.2+), before that live...
$('*your_form*').on('click', 'button', function(){
alert("click event");
});
Upvotes: 2
Reputation: 92933
You may simply need to use this instead:
$(document).on('click','button',function(){
alert("click event");
});
(jQuery 1.7 or higher)
Upvotes: 1
Reputation: 12437
you have to call using button id
$('#buttonid').click(function(){
alert("click event");
});
or button class
$('.buttonclassname').click(function(){
alert("click event");
});
Upvotes: 0