2016-07-24 121 views
0

我正在處理模式中的select2。幾周前我正在研究它。我已閱讀了一些帖子,但沒有任何解決方案適用於我。例如:select2不適用於模態

Select2 doesn't work when embedded in a bootstrap modal

Select2 not working inside bootstrap modal

的代碼是:

<div id="modal_sg" class="modal fade" style="overflow: hidden;"> 
<div class="modal-dialog"> 
    <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">Please select a corporation</h4> 
     </div> 
     <div class="modal-body"> 
      <form id="form_ag" class="form form-horizontal"> 
       <input type="hidden" style="display:none;" value="32" name="id"> 
       <div class="form-group"> 
        <label for="id_sg" class="control-label col-md-3">Corporation</label> 
        <div class="col-md-9"> 
         <select class="form-control select2" id="id_sg" name="id_sg"> 
          <option value="89">a</option> 
          <option value="115">b</option> 
          <option value="84">c</option> 
         </select> 
        </div> 
       </div> 
      </form> 
     </div> 
     <div class="modal-footer"> 
      <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button> 
      <button type="button" class="btn btn-primary" id="bt_modal_sg">Save</button> 
     </div> 
    </div><!-- /.modal-content --> 
</div><!-- /.modal-dialog --> 

的Javascript:

$('.select2').select2(
    {dropdownParent: $('#modal_sg')} 

);

的CSS:

.select2-container { 
width: 100% !important; 
padding: 0; 
} 

我使用select2-4.0.3。我不知道該怎麼解決這個問題,也不知道我的代碼有什麼問題。任何幫助將非常感激。提前致謝!

+0

你的問題到底是什麼? 「不工作」還不清楚。 – Shrike

+0

select2可以很好地工作,除非在模態中。當我點擊下拉菜單時,它會更改展開/摺疊符號,但我看不到任何下拉列表。我已經測試了我找到的所有解決方案,但沒有一個適合我。我確信我的代碼有問題,但我找不到它! – plectranthus

回答

0

使用dropdownParent是要走的路。我在Bootstrap對話框中成功使用了select2。但是從你的代碼中可以清楚你對話系統有哪些CSS屬性。是Bootstrap還是別的?

無論如何,您需要在dropdownParent選項中指定position:fixed的元素。它應該工作,至少在V4

2

這不是很漂亮,但爲我工作(選擇2的版本,你用什麼?):

.select-in-modal+.select2-container { 
    width: 100% !important; 
    padding: 0; 
    z-index:10000; 
} 

.select2-container--open { 
    z-index:10000; 
} 
-1

下面的代碼添加到JavaScript文件:

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

請閱讀[我如何寫出一個好答案](https://stackoverflow.com/help/how-to-answer) – Dwhitz

0

這適用於我!

$('select').select2({ 
    width: '100%' 
}); 
相關問題