How can I reuse one Bootstrap modal div?

喜欢而已 提交于 2019-11-27 19:11:36

After further research, I found a few Bootstrap issues mentioning this behaviour here and here. I've asked for issue 5514 to be reopened.

Meanwhile, this jQuery will patch up the problem*:

$('a[data-toggle="modal"]').on('click', function(){
    // update modal header with contents of button that invoked the modal
    $('#myModalLabel').html( $(this).html() );
    //fixes a bootstrap bug that prevents a modal from being reused
    $('#utility_body').load(
        $(this).attr('href'),
        function(response, status, xhr) {
            if (status === 'error') {
                //console.log('got here');
                $('#utility_body').html('<h2>Oh boy</h2><p>Sorry, but there was an error:' + xhr.status + ' ' + xhr.statusText+ '</p>');
            }
            return this;
        }
    );
});​

Please see http://jsfiddle.net/jhfrench/qv5u5/51/ for a working example.*

*-For some reason, sometimes when you click the button in the fiddle the modal will show blank. This is not a problem in the application I'm working with, so I suspect it's a problem unrelated to this question/answer.

Instead of having to write html markups of modal and manipulate it via javascript, I would use Bootstrap-Dialog to ease everything:

$('.modal-btn').click(function(event){
    var $link = $(this);
    new BootstrapDialog({
        title   :   'Load content of : ' + $link.attr('href'),
        content :   $('<div>Loading...</div>').load($link.attr('href')),
        buttons :   [{
            label   :   'Close',
            onclick :   function(dialog){
                dialog.close();
            }
        }, {
            label   :   'Save changes',
            cssClass:   'btn-primary',
            onclick :   function(dialog){
                alert('The content of the dialog is: ' + dialog.getBody().html());
                dialog.close();
            }
        }]
    }).open();

    event.preventDefault();
});

See here for a live demo, it loads the two urls you provided in your example: http://jsfiddle.net/txrM8/

See more about Bootstrap-Dialog: http://nakupanda.github.io/bootstrap-dialog/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!