shenk shenk - 6 months ago 29
jQuery Question

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 occur but with this code it does:

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


from what I understand they are the same thing, but the second tries to process the event every click on the page looking for the specified id. I tried putting it in a document ready block but that didn't help.

I don't understand why one works and the other does not.

Answer

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' ...)).

Comments