[Solved] JS selector on click not working for django model generated content [duplicate]


Your first code will also work if the element you reference is part of the document at that time, so make sure to put the script near the end of the document, or else wrap it in the ready handler:

$(function () {
    $('#delete-btn').on('click', function(){
        return confirm('Are you sure you want to delete this?');
    });
});

The second script ($(document).on('click' ...)) works, because the document is there from the start, so the handler is bound to it. At the time of the click, the event bubbles up to the document and the handler kicks in.

Dynamically created content

If your button is not in the document when the page loads, but is generated dynamically, the above code might still look for the button to soon. You mentioned django generates the button. It probably also captures an event when the document is ready, then queries the database, waits for its reply (in most cases this is asynchronous), and only then adds the button. If your code has already run by that time, it missed the button, and did not attach an event handler to it.

In that case, it is indeed a more solid solution to use the event delegation to the document level ($(document).on('click' ...)).

6

solved JS selector on click not working for django model generated content [duplicate]