on button click a html chunk comes by ajax and added in page. that html has some buttons. i tried to attach click event with those button using
on but did not.
$("#all-brokers").on("click", function (event) {
alert('click');
});
$('body').on('click', '#all-brokers', function () {
alert('click');
});
see my above two set of code where i try to attach click event with button. first one did not work but not throw any error. for first one when i click on button then alert did not fire but for second code when i just attach click event on document then it
worked.
1) please tell me why first code fail to attached click event with dynamic button which added in page by ajax ?
2) again why second approach worked fine ?
please try to give answer for my 2 questions. thanks
$("#all-brokers").on("click", function (event) {
alert('click');
});
TDP
1) please tell me why first code fail to attached click event with dynamic button which added in page by ajax ?
I tested your code, and it works fine on my site. Please check the id selector "all-brokers" is correct.
TDP
again why second approach worked fine ?
please try to give answer for my 2 questions. thanks
The second function attaches an event handler to only one element, the body, and the event only needs to bubble up one level (from the clicked all-brokers to body).
More information about the on event you can refer to this link:
.NET forums are moving to a new home on Microsoft Q&A, we encourage you to go to Microsoft Q&A for .NET for posting new questions and get involved today.
Member
77 Points
150 Posts
jquery on event issue to attach event with dynamic content
Jul 03, 2020 05:54 AM|TDP|LINK
on button click a html chunk comes by ajax and added in page. that html has some buttons. i tried to attach click event with those button using on but did not.
see my above two set of code where i try to attach click event with button. first one did not work but not throw any error. for first one when i click on button then alert did not fire but for second code when i just attach click event on document then it worked.
1) please tell me why first code fail to attached click event with dynamic button which added in page by ajax ?
2) again why second approach worked fine ?
please try to give answer for my 2 questions. thanks
Contributor
3370 Points
1409 Posts
Re: jquery on event issue to attach event with dynamic content
Jul 03, 2020 07:52 AM|samwu|LINK
Hi TDP,
I tested your code, and it works fine on my site. Please check the id selector "all-brokers" is correct.
The second function attaches an event handler to only one element, the body, and the event only needs to bubble up one level (from the clicked all-brokers to body).
More information about the on event you can refer to this link:
https://api.jquery.com/on/
Best regards,
Sam