locked
jquery on event issue to attach event with dynamic content RRS feed

  • Question

  • User-454825017 posted

    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

    Friday, July 3, 2020 5:54 AM

Answers

  • User288213138 posted

    Hi TDP,

    $("#all-brokers").on("click", function (event) {
    alert('click');
    });

    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.

    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:

    https://api.jquery.com/on/

    Best regards,

    Sam

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, July 3, 2020 7:52 AM