Search code examples
javascriptjquerydropzone.jsconfirm

How can I allow more than one uploaded file to be removed with dropzone using custom confirm dialogue?


I'm wanting to override the default way that Dropzone handles confirm dialogues when removing uploaded files and I'm almost there to a certain degree. Here's my code.

Dropzone.confirm = function(question, accepted, rejected) {
    showConfirm(question);
    $(document).on('click', '#accept-confirm', function() {
        hideConfirm();
        accepted();
    });
}

showConfirm = function(question) {
    var confirm_dialogue = '<div id="confirm-dialogue"><span class="question">'+question+'</span><button id="deny-confirm" class="button">Cancel</button><button id="accept-confirm" class="button">Yes</button></div>';
    $('body').append(confirm_dialogue).addClass('is-showing-confirm');
}

hideConfirm = function() {  
    $('body').removeClass('is-showing-confirm');
    let dialogue = document.getElementById('confirm-dialogue');
    dialogue.parentNode.removeChild(dialogue);
}

I can click my remove button, and my custom confirm is displayed. I can confirm the removal and the thumbnail is removed.

The problem is I can only do this for one image. For any other images I want to remove I just get the following error in my console.

Uncaught TypeError: Cannot read property 'removeChild' of null


Solution

  • You need to use .off() before using .on() because events which are applied to that button are called multiple times like,

    Dropzone.confirm = function(question, accepted, rejected) {
        showConfirm(question);
        $(document).off('click', '#accept-confirm').on('click', '#accept-confirm', function() {
            hideConfirm();
            accepted();
        });
    }
    

    Or you can use it once and place your function outside to the Dropzone.confirm like,

    Dropzone.confirm = function(question, accepted, rejected) {
         showConfirm(question);
    }
    // now it will be called once only,
    $(document).on('click', '#accept-confirm', function() {
        hideConfirm();
        accepted();
    });
    

    And for removing an element from DOM use .remove(),

    hideConfirm = function() {  
        $('body').removeClass('is-showing-confirm');
        $('#confirm-dialogue').remove();
    }
    

    You can check length of the element(which you want to delete) like,

    dialogue && dialogue.parentNode.removeChild(dialogue);