2013-07-16 43 views
11

我有一個輔助選擇從屬於一個主要選擇(選擇一家商店,然後選擇一個部門 - 相同的挑選一個國家,然後選擇一個國家)。select2將不會禁用或清除

我絕對無法得到select2('enable',false)和('data',null)方法的工作方式,無論我多少其他代碼都被剔除。

<select id="stores"> 
    <option value="foo">foo</option> 
</select> 
<select id="depts"> 
    <option value="bar">bar</option> 
</select> 

// ...some logic that selects a store, then fetches that store's depts ... 

$('#depts').select2('enable',false);// does not disable control 
$('#depts').select2('data',null); // does not clear control 

所以我不得不這樣做:

$('select#depts').empty(); // clears HTML element 
$('#depts').select2(); // re-enhances select w/ select2 
$('#depts').select2('disable',true); // disables 

它的行爲本身的jsfiddle,所以我甚至不能發佈一個例子並請求幫助。我只是...難倒了。

回答

0

,你會不會需要這樣的:

$( '#科指南')丙( '禁用',假);

一樣this question

+0

這個任務離子與您使用select2插件的鏈接不同,因此它不是一個簡單的選擇被禁用。 –

5

你可能遇到的錯誤選擇2 1104。不幸的是,它仍然是IE8-10的一個問題,但它不是select2的錯。問題是IE在元素禁用時不會觸發propertychange事件,也不會實現其他瀏覽器使用的MutationObserver功能。幸運的是,我寫了一個小的jQuery插件,它允許在元素禁用時觸發propertychange事件。你可以找到它here

$('#originalSelect').fireOnDisable().select2(); 
$('#originalSelect').prop('disabled', true); 

現在應該在IE8-10中工作。如果你需要支持IE6-7,那麼你就是你自己!

+0

在IE9/IE10中,disable屬性不適用於multile select2。 – Misi

+0

IE8-10沒有任何*屬性*觀察者,只有屬性觀察者 - 所以你可能會遇到一個問題,你設置屬性而不是屬性 - 在我的測試中,它使用jquery工作正常。prop(),但不是.attr() – cmcnulty

11

這對我的作品在所有瀏覽器:

$('#statusSelect').select2('destroy'); 
$('#statusSelect').prop('disabled', true); 
$('#statusSelect').select2(); 

這就給了你一個殘疾人選擇2輸入。

要重新啓用簡單:

$('#statusSelect').select2('destroy'); 
$('#statusSelect').prop('disabled', false); 
$('#statusSelect').select2(); 

不利的一面是,這會導致您的選擇框來改變外觀的一瞬間,當選擇2被破壞和重新應用。

另外,舊版本的select2中不支持「只讀」和「禁用」。

28
// to disable 
$('#statusSelect').select2('disable'); 

//to enable 
$('#statusSelect').select2('enable'); 
1

對於IE瀏覽器,你必須重新初始化選擇2啓用/禁用

// change action disable 
$('.custom-select').select2() 
.on("change", function(e) { 
    $('.custom-select').prop("disabled", true).select2(); //call select2 
}) 

// disable alternative 
$('.custom-select').prop("disabled", true).select2(); //call select2 
2

後,如果您有唯一的ID選擇2下拉框中,使用該ID,

$("#id-select2").attr("disabled", true); 
0

如果有人試圖在.net服務器代碼:

this.mySelect2elementID.Attributes.Add("disabled", "true");