NaszvadiG
3/4/2016 - 10:42 PM

Generic delete confirmation (jQuery and bootstrap 3.x)

Generic delete confirmation (jQuery and bootstrap 3.x)

// Example callback function
function removeAttachment(link) {
    // Do however you want to handle deleting 
    // We have the link element and can access it's data attributes
    // For example:
    $(link).parent().load($(link).data('url'));
}

$(document).ready(function() {
    // Now, when the button is clicked, setup the message, attach event with button 
    // and then show the modal
    $(document).on('click', 'a.remove', function(e) {
        e.preventDefault();
        var link = this;
        
        $('#delete-confirmation-msg').html($(this).data('message'));
        $('#delete-confirmation-yes').on('click', function() {
            var callback = $(link).data('callback');
            window[callback](link);

            $('#delete-confirmation').modal('hide');
        });

        $('#delete-confirmation').modal('show');
    });
    
    // While the modal is hiding, nedd to clear message and event
    $('#delete-confirmation').on('hidden.bs.modal', function (e) {
        $('#delete-confirmation-msg').empty();
        $('#delete-confirmation-yes').off();
    });
});
<!--
We need a generic Modal to ask for confirmation. 
Please note that:
    - we have a placeholder (#delete-confirmation-msg) for displaying delete message
    - Confirm positive button is #delete-confirmation-yes
-->
<div class="modal fade" id="delete-confirmation">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body">
                <p id="delete-confirmation-msg"></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" id="delete-confirmation-yes">Remove</button>
            </div>
        </div>
    </div>
</div>
<!--
The delete links should have a common class (.remove here) and the following data attributes:
    * data-url      - The link to remove target resource
    * data-message  - The message to show on confirmation modal
    * data-callback - The name of callback function that will be called if confirmation is positive
                      This funciton will receive the delete link element as argument                       
-->
<ul class="list-unstyled fileList">
    <li class="font-blue-steel" id="attachment-234">
        <a href="#" class="remove attachment" title="Remove this file"
                data-callback="removeAttachment"
                data-url="/the/url/to/delete/target/resource"
                data-message="Are you sure to delete this <b>InterestingThing<b/>?">
            <span class="glyphicon glyphicon-remove"></span> Delete
        </a>
    </li>
    <!-- More list items... -->
</ul>