Change Bootstrap modal option once it already exists

Viewed 26746

I'm using Bootstrap Modal. I declare it, I call it, I show it...everything seems to be ok.

But what if I have an already existing modal previously shown with "keyboard" property to false and I want to change it on the go? I mean something like:

First, I create a Modal doing this (as you can see, I declare the modal putting keyboard property to false):

$('#myModal').modal({
    show: false,
    backdrop: true,
    keyboard: false
});

But then I declare this event handler, that means that if "something" happens, I want the keyboard property to be set to true.

 $('#myModal').on('shown', function(e) {
    if (something){
        $('#myModal').modal({keyboard: true});
    }
 }

So, when I go

$("#myModal").show();

The event handler is not doing what it is supposed to, as I am not getting to close the modal once Escape key is pressed. But I am completely sure that "something" is true and I have checked and re-checked that $('#myModal').modal({keyboard: true}) is executed.

Any clue as to why this isn't updating the value of configuration option?

8 Answers

For Bootstrap 4.1

The options property should be replaced with _config.

E.G.

const modal = $('#modal');

/*
 |------------------------------------------------------------------------------
 | Now, let us assume you already opened the modal (via js or data attribute).
 | If you want to access the options and modify.
 |------------------------------------------------------------------------------
 */

// [Not Required] Let us see what the object is like.
console.log( modal.data('bs.modal')._config );

// Override the options to lock modal.
modal.data('bs.modal')._config.backdrop = 'static';
modal.data('bs.modal')._config.keyboard = false;

// [optional] You can also hide all data-dismiss buttons too.
modal.find("[data-dismiss='modal']").hide();

// Revert all actions above.
modal.data('bs.modal')._config.backdrop = true;
modal.data('bs.modal')._config.keyboard = true;
modal.find("[data-dismiss='modal']").show();

Setting backdrop and esckey not to close the modal when the modal is already open

$('div[name="modal"]').data('bs.modal').options.backdrop = 'static';
$('div[name="modal"]').off('keydown.dismiss.bs.modal');

Unset the backdrop and key esc purpose to not close the modal

$('div[name="user_profile_modal"]').data('bs.modal').options.backdrop = true;
$('div[name="user_profile_modal"]').data('bs.modal').escape();

For me this method works the best

$('#modal').on('hide.bs.modal', function () {
    return false;
});

It prevents modal from closing by any possible scenario:

  • pressing escape key
  • clicking outside the modal
  • clicking close button
  • and even using of $('#modal').modal('hide')
Related