简体   繁体   中英

Prevent bootstrap-3 modal from closing when the form has changes

I'm trying to prevent the bootstrap-3 modal from closing without warning when there are changes made to the form inside the modal. However when I listen to the events fired by the modal and return false it will prevent the modal from closing ever. Here's my code:

$(function() {
    $('body').live('shown.bs.modal', '#quickbutton-create', function () {
        $(this).find('#quickbutton-create form').monitor();
    });

    $('body').live('hide.bs.modal', '#quickbutton-create', function () {
        if ($(this).find('#quickbutton-create form').monitor('has_changed')) {
            if (!confirm('Are you sure?')) {
                return false;
            }
        }
    });
});

So in short, in this case; how do I prevent the modal from closing just this once.

Ok so I figured it out, instead of return false I needed to event.preventDefault()

jsfiddle here: http://jsfiddle.net/ACYBv/1/

$(function() {
    $('.modal').on('shown.bs.modal, loaded.bs.modal', function(e) {
        // set form state
        $(this).data('form-data', $(this).find('form').serialize());
    });

    $('.modal').on('hide.bs.modal', function(e) {        
        // check if the form data was changed since the modal was openened
        if($(this).data('form-data') != $(this).find('form').serialize()) {
            if(!confirm('you sure??')) {
                e.preventDefault();
            }
        }
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM