Search code examples
javascriptjquerybootbox

bootbox.js -> Show button in bootbox.dialog() only if condition is true


I use bootbox to create a dialog, but I want certain buttons only to show up under certain conditions.

I searched a lot, but found nothing helpful..

I define the bootbox like this:

bootbox.dialog({
   title: "title",
   message: "text",
   buttons: {
      btn1: {
         label: "Button 1",
         callback: function () {
            /* do something */                                
         }
      },
      btn2: {
         label: "Button 2",
         callback: function () {
            /* do something */                                
         }
      }       
});

How can I make the second Button only appear if(condition == true) ?

I also tried to remove the button afterwards like this:

bootbox.dialog({...})
if(!condition) {
   $('[data-bb-handler="btn2"]').remove();
}

But with no success.

Any idea appreciated!

Greetz


Solution

  • Just modify the buttons object that you pass to your bootbox, like so

      var buttons = {
        btn1: {
          label: "Button 1",
          callback: function() {
            /* do something */
          }
        },
      }
    
      // change here !!!    
      if (false)
        buttons.btn2 = {
          label: "Button 2",
          callback: function() {
            /* do something */
          }
        }
    
      bootbox.dialog({
        title: "title",
        message: "text",
        buttons: buttons
      });
    

    Fiddle - http://jsfiddle.net/7x5h91v2/