Skip to content Skip to sidebar Skip to footer

Js Selector On Click Not Working For Django Model Generated Content

This might be a dumb mistake but I have this code: $('#delete-btn').on('click', function(){ return confirm('Are you sure you want to delete this?'); }); the alert does not occ

Solution 1:

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(){
        returnconfirm('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' ...)).

Post a Comment for "Js Selector On Click Not Working For Django Model Generated Content"