2017-05-05 53 views
2

我想通過select2獲取用戶的偏好。在選擇一個選項時,其他select2中的選項應該禁用。如何禁用select2中的選項

樣品:

優選1: 選項1 選項2 選項3 選項4

偏好2: 選項1 選項2 選項3 選項4

偏好3 : 選項1 選項2 選項3 選項4

偏好4: 選項1 選項2 選項3 選項4

如果我選擇優先1選項1應該禁用偏好1,2,3,4 ,如果我在首選項2中選擇選項2,它應該在首選項1,2,3,4 中禁用,如果我在首選項3中選擇選項3,則應該在首選項中禁用1,2,3,4

如果我選擇選項4優先選擇2,它應該在首選項1,2,3,4和選項2中禁用在首選項3中選擇& 4.

我厭倦了各種實現,但卡住了。幫幫我。

HTML:

<div class="form-group col-md-6 m-t-sm"> 
    <label> Select Preference 1: </label> 
    <select class="form-control" id="pref1" name="pref1" style="width:100%"> 
    <option value=""> Select Campus Preference 1 </option> 
    <option value="N"> N </option> 
    <option value="O"> O </option> 
    <option value="R"> R </option> 
    <option value="S"> S </option> 
    </select> 
    <label id="pref1-error" class="error" for="pref1"></label> 
</div> 
. 
. 
. 

我現在的JS:

$('select[name*="pref"]').change(function(){ 

    // start by setting everything to enabled 
    $('select[name*="pref"] option').prop('disabled',false); 

    // loop each select and set the selected value to disabled in all other selects 
    $('select[name*="pref"]').each(function(){ 
     var $this = $(this); 
     $('select[name*="pref"]').not($this).find('option').each(function(){ 
      if($(this).attr('value') == $this.val()){    
       $(this).prop('disabled',true);    
      } 
     }); 
    }); 

}); 

回答

3

你可以禁用它使用下面的代碼

$("select").select2("destroy").select2(); 

$('select[name*="pref"]').change(function(){ 

    // start by setting everything to enabled 
    $('select[name*="pref"] option').prop('disabled',false); 

    // loop each select and set the selected value to disabled in all other selects 
    $('select[name*="pref"]').each(function(){ 
     var $this = $(this); 
     $('select[name*="pref"]').not($this).find('option').each(function(){ 
      if($(this).attr('value') == $this.val()){    
       $(this).prop('disabled',true);    
      } 
     }); 
    }); 
    $('select[name*="pref"]').select2("destroy").select2(); 
}); 
後重新初始化選擇

希望我能幫到你

+0

我沒有得到你@Vamshi –

+0

但是,一旦設置了所有四個選項,所有選項都被禁用,並且沒有重置選項的方法,對不對?除了頁面刷新。如果用戶想改變偏好,那麼最好的方法是什麼? – Vamshi

+0

@Vamshi你可以把一個名爲重置偏好的按鈕,使所有的選項 –