ElPiter ElPiter - 1 year ago 115
Javascript Question

Change Bootstrap modal option once it already exists

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):

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


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?

Answer Source

To change configuration settings on already initiated Bootstrap plugin, such as the Modal, you need to access the plugin object attached to the element, like $('#pluginElement').data['somePlugin'] and then set the options in it.

For the Modal, you need:

$('#myModal').data('modal').options.keyboard = true;

For Bootstrap 3 (as mentioned in comments by @Gerald ), you need bs.modal:

$('#myModal').data('bs.modal').options.keyboard = true;

JSFiddle Demo

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download