Search code examples
javascriptalertbootbox

Bootbox - how to dynamically add a button?


Once a user submits a form, an alert message should pop up and say "This might take up to a minute..."

Then, once the backend job is finished, the message text should change to 'Done' and an 'OK' button should be displayed.

I can create a dialog with a button, but I'm not sure how can I add it dynamically?

dialog = bootbox.alert({
        title: 'This might take up to a minute, please wait.',
        message: '<p><i class="fa fa-spin fa-spinner"></i> Submitting...</p>',
        centerVertical: true,
        backdrop: true,
        size: 'large',
        callback: function() {

        }
    }

)

How can I implement it? Do I need to create a new dialog or rewrite the existing one?

Bootbox.js


Solution

  • Here's an example based on your code, which uses a timeout to mimic an AJAX call:

    $(function(){
        let dialog = bootbox.alert({
          title: 'This might take up to a minute, please wait.',
          message: '<p><i class="fa fa-spin fa-spinner"></i> Submitting...</p>',
          centerVertical: true,
          size: 'large',
          closeButton: false,
          buttons: {
            ok: {
              className: 'btn-primary disabled'
            }
          },
          callback: function() {
    
          }
        });
    
        setTimeout(function(){ 
            dialog.find('.bootbox-body').html('<p>Done!</p>');
            dialog.find('.bootbox-accept').removeClass('disabled');
        }, 5000);
    });
    

    Assuming you're using the bootbox.alert helper and not a custom dialog, the OK button has the class .bootbox-accept, which we can use as a target. All content assigned to the message option is placed in a div with the .bootbox-body class, which, again, we can target.

    This is the same process, for the most part, as the .init() example: http://bootboxjs.com/examples.html#custom-dialog-init

    If you want to automatically dismiss the dialog when your background process is done, the overlay example pretty much does just that:

    let timeout = 3000; // 3 seconds
    let dialog = bootbox.dialog({
        message: '<p class="text-center mb-0">Please wait while we do something...</p>',
        closeButton: false
    });
    
    setTimeout(function () {
        dialog.modal('hide');
    }, timeout);