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?
Setting backdrop and esckey not to close the modal when the modal is already open
Unset the backdrop and key esc purpose to not close the modal
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 theoptions
in it.For the Modal, you need:
JSFiddle Demo (old)
Waiting Modal Example
Another option if you do not know if the modal has already been opened or not yet and you need to configure the modal options (Bootstrap 3):
Thanks @nokturnal
A bit beyond the scope of the OP, but this is now twice I have searched for the same solution (my memory is crap) and twice that I came across this question which led me to my eventual answer. My issue was how to make an already init'ed and displayed modal, which was "closeable", into an "uncloseable" model. In the rare even that another user needs this answer, here is what I did based on the accepted answer:
*bootstrap3 used
Notice that I didn't change the options.keyboard property to false (followed by calling escape()) as suggested above. I could not get that to work, so after looking the Bootstrap source, I saw that all it was doing was simply removing an event listener for 'keyup.dismiss.bs.modal'.
To re-enabled things (in my scenario, when the model is hidden):
This seems COMPLETELY clumsy and will for sure break in coming versions of Bootstrap, but works for now...
Cheers :)
You can also add an attribute in your HTML tag: data-keyboard="false"
<div id="myModal" class="modal hide fade" data-keyboard="false" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"></div>
It works for me!
For bootstrap4
To disable closing modal on escape button:
To disable closing modal on clicking on backdrop:
As warned by nocturnal, this may break in the future versions of bootstrap.