Change Bootstrap modal option once it already exists
Asked Answered
F

9

41

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?

Food answered 4/8, 2012 at 7:36 Comment(0)
G
50

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;

JSFiddle Demo (old)


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

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

Waiting Modal Example

Gearldinegearshift answered 4/8, 2012 at 7:36 Comment(7)
This works great between modal launches, but what about when the modal is already open? I moved the toggle button inside the modal here: jsfiddle.net/DCR4Y/10Birgit
@ChrisBarr I showed how to do this in another answer:Convert a Twitter Bootstrap Uncloseable Modal into a Closeable One. It depends on which properties of the modal you want to edit. For the keyboard property, you need to call the escape() method after you change the value of the property on the object in order to reinitialize it.Gearldinegearshift
Hi merv, Your solution helped me a lot. I have one problem. I am closing the modal using backdrop option on clicking outisde the modal. In modal i have a form if there are any changes in form i dont want to close the form even if they click outside. Can you see my issue #29027547Settee
for bootstrap 3, data is named as 'bs.modal'Voluptuary
Bootstrap is broken in the fiddle so I created a new example: codeply.com/go/cFSzteMbxSProsthesis
@ZimSystem Nice example! Next time just add it directly (it's a community wiki). BTW, I also fixed my outdated fiddle.Gearldinegearshift
I created a feature request to add an official way to change modal options after creation. github.com/twbs/bootstrap/issues/35664Pigeontoed
O
24

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

$('#modal').off('keyup.dismiss.bs.modal'); // disable escape key
$('#modal').data('bs.modal').options.backdrop = 'static';
$('#modal button.close').hide();

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

$('#modal').on('hidden.bs.modal', function (e) {
    $(this).data('bs.modal').escape(); // reset keyboard
    $(this).data('bs.modal').options.backdrop = true;
    $('button.close', $(this)).show();
});

This seems COMPLETELY clumsy and will for sure break in coming versions of Bootstrap, but works for now...

Cheers :)

Offish answered 18/12, 2013 at 2:11 Comment(1)
Sometimes 'keyup.dismiss.bs.modal' does not work, so you can use 'keydown.dismiss.bs.modal' insteadNorthwards
N
10

For bootstrap4

To disable closing modal on escape button:

$('#myModal').off('keydown.dismiss.bs.modal');

To disable closing modal on clicking on backdrop:

$('#myModal').data('bs.modal')._config.keyboard = false;

As warned by nocturnal, this may break in the future versions of bootstrap.

Nudibranch answered 13/3, 2018 at 2:19 Comment(3)
Disabling closing by clicking on the backdrop didn't work for me. Use this instead: $('#myModal').data('bs.modal')._config.backdrop = 'static';Faradmeter
The backdrop disabling works for me, but the [Esc] disabling does not work. Bootstrap 4.2.1.Courtship
Actually, it works, but the backdrop disabling is permanent, whereas the [Esc] disabling needs to be done every time upon modal open.Courtship
E
5

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();
Ey answered 20/8, 2020 at 6:33 Comment(0)
R
3

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();
Recrimination answered 19/10, 2018 at 15:53 Comment(0)
T
2

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!

Tuscany answered 22/3, 2013 at 16:8 Comment(0)
L
2

For Bootstrap 5:

You get the instance of an already existing modal by calling bootstrap.Modal.getInstance(domEl)

let domEl = $('#myModal')[0];
let bootstrapInstance = bootstrap.Modal.getInstance(domEl);
bootstrapInstance._config.show = false;
bootstrapInstance._config.backdrop = true;
bootstrapInstance._config.keyboard = false;
Loquitur answered 9/8, 2023 at 14:54 Comment(0)
N
1

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

var $modal = $('#modal');
var keyboard = false; // Prevent to close by ESC
var backdrop = 'static'; // Prevent to close on click outside the modal

if(typeof $modal.data('bs.modal') === 'undefined') { // Modal did not open yet
    $modal.modal({
        keyboard: keyboard,
        backdrop: backdrop
    });
} else { // Modal has already been opened
    $modal.data('bs.modal').options.keyboard = keyboard;
    $modal.data('bs.modal').options.backdrop = backdrop;

    if(keyboard === false) { 
        $modal.off('keydown.dismiss.bs.modal'); // Disable ESC
    } else { // 
        $modal.data('bs.modal').escape(); // Resets ESC
    }
}

Thanks @nokturnal

Northwards answered 24/2, 2018 at 3:24 Comment(0)
B
0

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')
Borderland answered 3/7, 2021 at 17:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.