417

When I use a select2 (input) in bootstrap modal, I can't type anything into it. It's like disabled? Outside the modal select2 works fine.

enter image description here

Working example: http://jsfiddle.net/byJy8/1/ code:

<!-- Modal -->
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h3 id="myModalLabel">Panel</h3>
    </div>
    <div class="modal-body" style="max-height: 800px">          
      <form class="form-horizontal">
        <!-- Text input-->
        <div class="control-group">
            <label class="control-label" for="vdn_number">Numer</label>
            <div class="controls">
                <!-- seleect2 -->
                <input name="vdn_number" type="hidden" id="vdn_number"  class="input-large" required=""  />
            </div>
        </div>
      </form>    
    </div>
    <div class="modal-footer">
        <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
        <button class="btn btn-primary">Save changes</button>
    </div>
</div>

JS

$("#vdn_number").select2({
    placeholder: "00000",
    minimumInputLength: 2,
    ajax: {
        url: "getAjaxData/",
        dataType: 'json',
        type: "POST",
        data: function (term, page) {
            return {
                q: term, // search term
                col: 'vdn'
            };
        },
        results: function (data) { // parse the results into the format expected by Select2.
            // since we are using custom formatting functions we do not need to alter remote JSON data
            return {results: data};
        }
    }
});

answers:

here you can find a quick fix

and here is 'the right way': Select2 doesn't work when embedded in a bootstrap modal

3
  • 2
    That is, removing the attribute tabindex="-1" from the element. Aug 3, 2017 at 7:00
  • dboswell's answer is the right solution, BUT, the dropdownParent should not be on the root div, but deeper, for example the div with class modal-content, otherwise the dropdown positions get messed up when scrolling the modal. Nov 4, 2018 at 1:44
  • My solution which worked with me Feb 3 at 19:03

36 Answers 36

717

Ok, I've got it to work.

change

<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h3 id="myModalLabel">Panel</h3>
    </div>
    <div class="modal-body" style="max-height: 800px">

to

<div id="myModal" class="modal hide fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h3 id="myModalLabel">Panel</h3>
    </div>
    <div class="modal-body" style="max-height: 800px">

(remove tabindex="-1" from modal)

8
  • 27
    May be there another solution? Because modal window then won't close by Esc key.
    – woto
    Oct 20, 2013 at 15:47
  • 23
    removing tabindex="-1" didn't work form me. I've just changed <div class="modal-body"> to <div class="modal-body" style="overflow:hidden;">
    – Wissem
    Nov 27, 2013 at 8:49
  • 3
    Please select pymarco answer as the correct one, this solutions breaks ESC key, his doesn't. Nice try though.
    – goyote
    Apr 25, 2017 at 10:11
  • @woto have you find any other solution? I had the same issue like yours. after removing tabindex="-1" my model did not close on Esc key. Jun 28, 2017 at 9:26
  • 2
    Is there any sideeffect of removing taxindex? Jan 31, 2018 at 14:45
350

For Select2 v4:

Use dropdownParent to attach the dropdown to the modal dialog, rather than the HTML body.

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        <select id="select2insidemodal" multiple="multiple">
          <option value="AL">Alabama</option>
            ...
          <option value="WY">Wyoming</option>
        </select>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>


<script>

$(document).ready(function() {
  $("#select2insidemodal").select2({
    dropdownParent: $("#myModal")
  });
});

</script>

This will attach the Select2 dropdown so it falls within the DOM of the modal rather than to the HTML body (the default). See https://select2.org/dropdown#dropdown-placement

11
  • 35
    This worked for me (with v4.0.2), but I had to use dropdownParent: $("#myModal"), not dropdownParent: "#myModal". Apr 12, 2016 at 7:58
  • @Kevin Brown: your update on the post is not accurate as dropdownParent: $("#myModal") is STILL required for enabling typing in on modal using version v4.0.1; I've just run the test. You may revert your update in order to make @dboswell's answer still relevant and meaningful. Aug 29, 2016 at 17:07
  • @nyed the only edit I made was that I forced dropdownParent to take a jQuery object. The update was already there, and I'm not in a position to verify it. Aug 29, 2016 at 17:09
  • 9
    FWIW, in my case I needed to set the dropdownParent to the body of the modal, attaching it to the modal itself did not bring the z-index up high enough. e.g. dropdownParent: $('.modal-body', '#myModal') Dec 14, 2017 at 18:03
  • 2
    @DrewInTheMountains I also had issues setting the dropdownParent to the root of the modal, it's indeed better to choose the body, otherwise you get really bad positioning bugs when scrolling. I set mine to the div with class modal-content and it works like a charm! Nov 4, 2018 at 1:47
224

I found a solution to this on github for select2

https://github.com/select2/select2/issues/1436

For bootstrap 3, the solution is:

$.fn.modal.Constructor.prototype.enforceFocus = function() {};

Bootstrap 4 renamed the enforceFocus method to _enforceFocus, so you'll need to patch that instead:

$.fn.modal.Constructor.prototype._enforceFocus = function() {};

Explanation copied from link above:

Bootstrap registers a listener to the focusin event which checks whether the focused element is either the overlay itself or a descendent of it - if not it just refocuses on the overlay. With the select2 dropdown being attached to the body this effectively prevents you from entering anything into the textfield.

You can quickfix this by overwriting the enforceFocus function which registers the event on the modal

6
  • I just fixed this for using CKEditor inside a Bootstrap 2.3.2 modal window. This function is called a lot, so if you modify the if statement you have to be really careful not to bash your browser; I suggest placing any addition clauses inside the existing if - not appending them to that if. (e.g. if (existing conditions) { if (your conditions) { Hope that helps.
    – JonRed
    Oct 25, 2013 at 3:34
  • 5
    where do I put this code and what function should it address? Sorry, JS noob here, I tried making this a part of the select2 JS or placing it at top / end of the page, all without success. $.fn.modal.Constructor.prototype.enforceFocus = $.noop;
    – Armitage2k
    Nov 27, 2016 at 0:59
  • 6
    in bootstrap 4, instead of globally overwriting the enforceFocus function..If we set data-focus="false" to a modal (<div class="modal fade" id="mymodal" tabindex="-1" data-focus="false" role="dialog" aria-hidden="true">) _enforceFocus will never be called for this modal. tested in bootstrap 4.1.3 and it worked...original answer github.com/twbs/bootstrap/issues/19971#issuecomment-275901368 Jan 3, 2019 at 8:13
  • for fix scroll bug and search input bug in bootstrap modal you see my answer in page 2 Mar 21, 2022 at 2:13
  • Complementing @Ashokbharathi. If you need to apply this effect to a single modal instance (having access to base code), you can inspect for data-focus attribute on bootstrap.js:1011 and wrap the method call into an if statement. Tested on 3.3.7 Jul 29, 2022 at 16:46
70

Set the dropdownParent. I had to set it on .modal-content within the modal or the text would end up centered.

$("#product_id").select2({
    dropdownParent: $('#myModal .modal-content')
});
3
  • 8
    The .modal-content really make a difference. Thanks for pointing out 👍
    – Js Lim
    Apr 18, 2019 at 4:10
  • If you using this for multiple modals you can use dropdownParent: $(".modal-body , .modal-body1") Mar 20, 2021 at 15:59
  • 1
    works also in Bootstrap 5
    – cwhisperer
    May 18, 2022 at 12:00
52

Just remove tabindex="-1" and add style overflow:hidden

Here is an example:

<div id="myModal" class="modal fade" role="dialog" style="overflow:hidden;">
    <!---content modal here -->
</div>
5
  • 2
    it works but when I have long modal I can't scroll down ! Mar 17, 2018 at 16:40
  • Tried removing the tabindex but was not enought. Adding overflow: hidden is useful if the modal box is long...
    – Plasebo
    Apr 2, 2018 at 11:17
  • Worked for me removing the tab index attribute.
    – Glen
    Jun 4, 2018 at 11:25
  • 2
    Just FYI: removing tab-index attr will remove the ability of closing modal popup by esc button.
    – curiousBoy
    Jul 28, 2018 at 7:10
  • if you are using yii2 bootstrap modal use options settings: 'options' => ['tabindex' => false, "style"=>"overflow:hidden;"],
    – Opad
    Oct 13, 2018 at 17:12
44
.select2-close-mask{
    z-index: 2099;
}
.select2-dropdown{
    z-index: 3051;
}

This is my solution with select2 4.0.0. Just override the css right below the select2.css import. Please make sure the z-index is greater than your dialog or modal. I just add 2000 on the default ones. Cause my dialogs' z-index are about 1000.

5
  • 2
    None of the solutions worked for select2 4.0.0 except this. Thanks a lot.
    – Neel
    Jun 26, 2015 at 10:15
  • The same issue occurs if Select2 (v4.0.0) is in a popover. In bootstrap.css the z-index of .popover is set to 1060 so this fix works as well. I like it because it's simple and it solves the problem the same way the problem was created: z-index set in a style sheet.
    – Paul
    Jul 2, 2015 at 18:02
  • I've added the above in my css file, but it has no changes. I'm using jQuery Mobile. Any suggestions please? Feb 20, 2016 at 7:03
  • @Sahil 1. make sure it's successfully overridden the original ones. simple way is add this after all the default css files2.check the z-index, ensure it's larger than the dialog's
    – Diluka W
    Feb 22, 2016 at 8:55
  • Remove tabindex="-1" from modal to make this solution work.
    – RenanStr
    Oct 17, 2019 at 13:50
19

Answer that worked for me found here: https://github.com/select2/select2-bootstrap-theme/issues/41

$('select').select2({
    dropdownParent: $('#my_amazing_modal')
});

Also doesn't require removing the tabindex.

0
17

In my case I had the same problem with two modals and all was resolved using:

$('.select2').each(function() { 
    $(this).select2({ dropdownParent: $(this).parent()});
})

As in the project issue #41 an user said.

2
  • I added dropdownParent: $('#my_modal .select2_parent') as your answer and .select2-container{top:100% !important;} to fix my same issue. Tried all the solutions, but only solved by this. Jul 28, 2021 at 16:15
  • Best solution for multiple modal. Thanks Aug 21 at 14:19
14

According to the official select2 documentation this issue occurs because Bootstrap modals tend to steal focus from other elements outside of the modal.

By default Select2 attaches the dropdown menu to the element and it is considered "outside of the modal".

Instead attach the dropdown to the modal itself with the dropdownParent setting:

$('#myModal').select2({
   dropdownParent: $('#myModal')
});

See reference: https://select2.org/troubleshooting/common-problems

1
  • Good. it was not working with magnific popup, now after adding dropdownParent option its working fine. Nov 18, 2019 at 14:44
13

I had the same issue, updating z-index for .select2-container should do the trick. Make sure your modal's z-index is lower than select2's.

.select2-container {
    z-index: 99999;
}

Updated: In case above code doesn't work properly, also remove tabindexes from your modal as @breq suggested

3
  • 1
    you need to implement this with @breq answer to make it works.
    – Ryan Arief
    Jun 11, 2017 at 3:40
  • I find it quite nice and easy over attaching to parent model.
    – veekram
    May 20, 2021 at 17:02
  • Ok. But, z-index style affects visibility of other raised elements such as side nav.
    – CodesmithX
    Sep 7 at 3:46
11

This Problem Sloved Working For Me Single Jquery Function

$('#myModal .select2').each(function() {  
   var $p = $(this).parent(); 
   $(this).select2({  
     dropdownParent: $p  
   });  
});
0
11

For bootstrap3 versions, just use this code on document ready:

$(document).ready(function(){
    $.fn.modal.Constructor.prototype.enforceFocus = function () {};
});
1
  • 1
    The proper function name is "$(document).ready". So code should be like: $(document).ready(function () { $.fn.modal.Constructor.prototype.enforceFocus = function () { }; }); Nov 2, 2017 at 14:04
10

I had a similar problem and I fixed with

    $('#CompId').select2({
              dropdownParent: $('#AssetsModal')
    });

and modal with select

    <div class="modal fade" id="AssetsModal" role="dialog" 
    aria-labelledby="exampleModalCenterTitle" 
    aria-hidden="true"  style="overflow:hidden;" >
<div class="modal-dialog modal-dialog-centered" role="document">
  <div class="modal-content">
      <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLongTitle" >Добави активи</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
      </div>
      <div class="modal-body">
          <form role="form" action="?action=dma_act_documents_assets_insert&Id=<?=$ID?>" 
                  method="post" name="dma_act_documents_assets_insert" 
                  id="dma_act_documents_assets_insert">
            <div class="form-group col-sm-12">
                  <label for="recipient-name" class="col-form-label">Актив:</label>
                  <span style="color: red">*</span>
                          <select class="form-control js-example-basic-single col-sm-12" 
                                 name="CompId" id="CompId">
                                  <option></option>
                          </select>
              </div>
          </form>
      </div>
  </div>
</div>

but I don't know why the select menu is smaller than other fields enter image description here

and it starting like that when start using select2. When I remove it, all is ok.

Is there some one to share some experince about that.

Thanks.

1
  • 1
    use style width: 100% and it will be in full width. May 19, 2022 at 7:14
8
$('.modal').on('shown.bs.modal', function (e) {
    $(this).find('.select2me').select2({
        dropdownParent: $(this).find('.modal-content')
    });
})
2
  • Worked for bootstrap 5
    – Rishabh
    Jan 7, 2022 at 9:19
  • Best solution so far as it only changes the parent of the select inside the modal.
    – CodesmithX
    Sep 7 at 3:46
5

change select2.css file

z-index: 9998;
...
z-index: 9999;
...
z-index: 10000;

to

z-index: 10000;
...
z-index: 10001;
...
z-index: 10002;
1
  • That's the only one works for me (jquery-ui-1.10.3.css, jquery-ui-1.9.1.js and select2 3.4.0). I have 2 jquery UI dialogs one on top of the other and select2 on the second one. Also I have put //allow interaction of select2, date and time picker on jQuery UI dialog $.ui.dialog.prototype._allowInteraction = function(e) { return !!$(e.target).closest('.ui-dialog, .ui-datepicker, .select2-drop').length; }; I have no idea if this help or not.
    – Adrian P.
    Feb 9, 2016 at 17:29
5

Just to understand better how tabindex elements works to complete accepted answer :

The tabindex global attribute is an integer indicating if the element can take input focus (is focusable), if it should participate to sequential keyboard navigation, and if so, at what position. It can take several values:
  -a negative value means that the element should be focusable, but should not be reachable via sequential keyboard navigation;
  -0 means that the element should be focusable and reachable via sequential keyboard navigation, but its relative order is defined by the platform convention;
  -a positive value means should be focusable and reachable via sequential keyboard navigation; its relative order is defined by the value of the attribute: the sequential follow the increasing number of the tabindex. If several elements share the same tabindex, their relative order follows their relative position in the document.

from : Mozilla Devlopper Network

5

to use bootstrap 4.0 with server-side(ajax or json data inline), you need to add all of this:

$.fn.modal.Constructor.prototype._enforceFocus = function() {};

and then when modal is open, create the select2:

  // when modal is open
  $('.modal').on('shown.bs.modal', function () {
            $('select').select2({
                  // ....
            });
  });
3
  • 2
    instead of globally disabling focus functionality of bootstrap modal, you can specify data-focus="false" attribute on modal html code. https://getbootstrap.com/docs/4.5/components/modal/#options
    – itsyub
    Aug 11, 2020 at 19:29
  • 1
    None of other answers worked for me except this one, if you are opening the modal manually then this answer is the one to go
    – VeRJiL
    Nov 29, 2020 at 23:13
  • 1
    I just added " $.fn.modal.Constructor.prototype._enforceFocus = function() {}; this line and it worked for me. Thanks
    – Roushan
    Apr 19, 2021 at 12:40
3

If you have a problem with the iPad keyboard which hide the bootstrap modal while clicking on the select2 input, you can resolve this by adding the following rule after the initialization of the select2 input :

if (navigator.userAgent.match(/iPhone|iPad|iPod/i)) {
   var styleEl = document.createElement('style'), styleSheet;
   document.head.appendChild(styleEl);
   styleSheet = styleEl.sheet;
   styleSheet.insertRule(".modal { position:absolute; bottom:auto; }", 0);
   document.body.scrollTop = 0; // Only for Safari
}

Taken from https://github.com/angular-ui/bootstrap/issues/1812#issuecomment-135119475

EDIT: If your options are not shown properly, you need to use the dropdownParent attribute when initializing select2 :

$(".select2").select2({
    dropdownParent: $("#YOURMODALID")
});

Good luck (:

3

Based on @pymarco answer I wrote this solution, it's not perfect but solves the select2 focus problem and maintain tab sequence working inside modal

    $.fn.modal.Constructor.prototype.enforceFocus = function () {
        $(document)
        .off('focusin.bs.modal') // guard against infinite focus loop
        .on('focusin.bs.modal', $.proxy(function (e) {
            if (this.$element[0] !== e.target && !this.$element.has(e.target).length && !$(e.target).closest('.select2-dropdown').length) {
                this.$element.trigger('focus')
            }
        }, this))
    }
3

I solved this generally in my project by overloading the select2-function. Now it will check if there is no dropdownParent and if the function is called on an element that has a parent of the type div.modal. If so, it will add that modal as the parent for the dropdown.

This way, you don't have to specify it every time you create a select2-input-box.

(function(){
    var oldSelect2 = jQuery.fn.select2;
    jQuery.fn.select2 = function() {
        const modalParent = jQuery(this).parents('div.modal').first();
        if (arguments.length === 0 && modalParent.length > 0) {
            arguments = [{dropdownParent: modalParent}];
        } else if (arguments.length === 1
                    && typeof arguments[0] === 'object'
                    && typeof arguments[0].dropdownParent === 'undefined'
                    && modalParent.length > 0) {
            arguments[0].dropdownParent = modalParent;
        }
        return oldSelect2.apply(this,arguments);
    };
    // Copy all properties of the old function to the new
    for (var key in oldSelect2) {
        jQuery.fn.select2[key] = oldSelect2[key];
    }
})();
1
  • This actually was the only solution i got to work.. I am using Metronic HTML theme probably why
    – eqiz
    Apr 24 at 6:45
3

Remove tabindex="-1" from modal. I checked this solution and it's worked.

Ref: https://github.com/select2/select2-bootstrap-theme/issues/41

3

This will work for all

body .select2-container {
    z-index: 9999 !important;
}
3

Use this code on your page

$(function () {
    $(".select2").select2({
        dropdownParent: $('#myModal')
    });

    $("#myModal").on('change', '#vdn_number', function () {
        var term = $(this).val();
        ajax: ({
            url: "getAjaxData/",
            dataType: 'json',
            type: "POST",
            data: function (term, page) {
                return {
                    q: term, // search term
                    col: 'vdn'
                };
            },
            results: function (data) { // parse the results into the format expected by Select2.
                // since we are using custom formatting functions we do not need to alter remote JSON data
                return { results: data };
            }
        });
    });
});

I think this will help you

1
  • select2 works itself when we place the component on the main page, whereas on the model it doesn't therefore the answer $(".select2").select2({ dropdownParent: $('#myModal') }); helps to solve the issue Nov 29, 2021 at 20:17
2
$("#IlceId").select2({
    allowClear: true,
    multiple: false,
    dropdownParent: $("#IlceId").parent(),
    escapeMarkup: function (m) {
        return m;
    },
});

this code is working. Thank you.

2

Okay, I know I'm late to the party. But let me share with you what worked for me. The tabindex and z-index solutions did not work for me.

Setting the parent of the select element worked as per the common problems listed on select2 site.

2

Use Select2 Bootstrap 5 Theme in Bootstrap Modal like this:

  1. fix select2 & bootstrap modal search input bug.
  2. fix select2 & bootstrap modal scroll bug after select option.

jQuery(function() {

  $('.my-select2').each(function() {
    $(this).select2({
      theme: "bootstrap-5",
      dropdownParent: $(this).parent(), // fix select2 search input focus bug
    })
  })

  // fix select2 bootstrap modal scroll bug
  $(document).on('select2:close', '.my-select2', function(e) {
    var evt = "scroll.select2"
    $(e.target).parents().off(evt)
    $(window).off(evt)
  })

})
<!DOCTYPE html>
<html>

<head>
  <!-- Styles -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" />
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" />
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/select2-bootstrap-5-theme.min.css" />

  <!-- Scripts -->
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>

</head>

<body>

  <!-- Button trigger modal -->
  <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
  Launch demo modal
</button>

  <!-- Modal -->
  <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          Select2 v4.1

          <select class="my-select2">
            <option>Test 1</option>
            <option>Test 2</option>
            <option>Test 3</option>
            <option>Test 4</option>
            <option>Test 5</option>
            <option>Test 6</option>
            <option>Test 7</option>
            <option>Test 8</option>
            <option>Test 9</option>
            <option>Test 10</option>
          </select>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary">Save changes</button>
        </div>
      </div>
    </div>
  </div>
</body>

</html>

1

If you use jquery mobile popup you must rewrite _handleDocumentFocusIn function:

$.mobile.popup.prototype._handleDocumentFocusIn = function(e) {
  if ($(e.target).closest('.select2-dropdown').length) return true;
}

1
  • I'm using jQuery Mobile and have embedded Select2 in a popup. The code you have provided works good on a PC browser. But when I run this code on a mobile browser, the popup closes and reopens when any value is selected. Can you suggest any changes I need to make? Feb 20, 2016 at 7:03
1

I have the same problem with the select2 in bootstrap modal, and the solution was to remove the overflow-y: auto; and overflow: hidden; from .modal-open and .modal classes

Here is the example of using jQuery to remove the overflow-y:

$('.modal').css('overflow-y','visible');
$('.modal').css('overflow','visible');
1

i had this problem before , i am using yii2 and i solved it this way

$.fn.modal.Constructor.prototype.enforceFocus = $.noop;
1

I had a semi-related issue in an application so I'll put in my 2c.

I have multiple modals with forms containing select2 widgets. Opening modal A, then another modal inside modal A, would cause select2 widgets inside modal B to disappear and fail to initialize.

Each of these modals were loading the forms via ajax.

The solution was to remove the forms from the dom when closing a modal.

$(document).on('hidden.bs.modal', '.modal', function(e) {
    // make sure we don't leave any select2 widgets around 
    $(this).find('.my-form').remove();
});

Not the answer you're looking for? Browse other questions tagged or ask your own question.