Select2 does not work inside boot modal

I am trying to use select2 inside bootstrap modal, but it does not get focus automatically, and the down and up arrows do not work for a populated list.

The same select2 works when I put it outside a modal popup.

When I searched, I found that many are facing the same problem and found this message

Select2 does not work if it is built into the boot mod

I implemented both solutions from it

  • Removed tabindex from a modal popup.
  • The commented code for the enforceFocus function in the enforceFocus file.

But it still does not work! Any idea what I can still skip?

Edit1

Works on firefox when tabindex is removed from a modal div, but not with IE9

Edit2

I found that tabindex removal is not actually recognized by IE9 because I can still hide the popup using the escape key in IE, but not in Firefox.

+7
jquery-select2
source share
7 answers

Problem detected!

Actually, I opened the html modal attributes on the button, for example

  data-target="#modalAttachment" 

while I have to use javascript code to open modality to make enforceFocus change when I started using it to open modal, enforceFocus function changed work

 $('#modalAttachment').modal('show'); 

Thanks!

-4
source share

put this somewhere in your JS:

  //fix modal force focus $.fn.modal.Constructor.prototype.enforceFocus = function () { var that = this; $(document).on('focusin.modal', function (e) { if ($(e.target).hasClass('select2-input')) { return true; } if (that.$element[0] !== e.target && !that.$element.has(e.target).length) { that.$element.focus(); } }); }; 
+14
source share

I changed:

 <div class="modal fade bd-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true"> 

to the next:

 <div class="modal fade bd-example-modal-lg" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true"> 

That is, removing the tabindex="-1" attribute from the element.

+1
source share

it will do the trick and it worked for me

 $.fn.modal.Constructor.prototype.enforceFocus = $.noop; 
0
source share

I tried setting the z-index for the select2 select option and it worked for me. Here is what I did:

 .select2-container.select2-container--default.select2-container--open { z-index: 5000; } 
0
source share

try it

 <div class="col-sm-8" id="select"> <select type="text" class="form-control" id="helloselect" data-width="100%" name="helloselect"> <option>Hello</option> <option>Hola</option> <option>Hallo</option> </select> </div> 

and script

 $("#helloselect").select2({dropdownParent: $("#select")}); 
0
source share

Use the following code. This will solve your mistake.

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

All Articles