我開始接觸這個插件的時候,找了很多中文資料,都和下面這篇文章大同小異。
相關jquery 多選下拉框插件中文介紹: http://www.cnblogs.com/xinchuang/archive/2013/05/24/3096757.html
英文好的童鞋一定要看看官網,中文資料實在是太少,我也是因此才想寫一些中文資料分享給大家。
jquery multiselect 的官方英文網站:http://www.erichynds.com/blog/jquery-ui-multiselect-widget
官方提供的demo:http://www.erichynds.com/examples/jquery-ui-multiselect-widget/demos/
源代碼也可以在英文官網中找到,也可以從文中第一篇中文資料提供的下載地址中下載。
首先說一下如何獲取下拉框的值
要獲取下拉框的值,僅靠 $('#selectid').val() 確實不行,而且我使用$('#selectid').val() 遇到了一個問題
就是: 選中的option的值是01 , 結果$('#selectid').val()的結果是0,1。
正確獲取每一個選中的option的值的方法,官網中有明確的介紹:
Retrieve all selected values?
The easiest way is to call val()
on the select box:
var values = $("select").val();
The same can be accomplished using the multiselect API. Call the getChecked
method and map a new array:
var array_of_checked_values = $("select").multiselect("getChecked").map(function(){
return this.value;
}).get();
array_of_checked_values是個數組,我們可以再加個join(',') 拼成一個用逗號隔開的字符串。
我們的項目中,需要用ajax動態加載這個多選框的內容,但是我發現動態加載后,多選框會默認選中第一個option,客戶提出不可以默認選中
那么第二個問題來了,如何取消默認選中 ,還是要查官網!
Methods
After an instance has been initialized, interact with it by calling any of these methods:
// example:
$("#multiselect").multiselect("method_name");
閱讀發現,可以這樣手動觸發多選框自帶的方法,官網中有method_name列表,我這就不貼出來了。
我調用了uncheckAll方法,把默認的勾選去掉了。
第三個問題又來了,我獲取下拉框值的時候,發現還是能取到值,也就是說uncheckAll僅僅是把checkbox勾選去掉了,
option還是選中的! 那么如何獲取正確的值呢?再次閱讀官網發現
Manually check or uncheck a checkbox?
The checkboxes can be accessed after calling the "widget" method. Simply manually trigger the NATIVE click event on them:
// manually check (or uncheck) the third checkbox in the menu:
$("select").multiselect("widget").find(":checkbox").each(function(){
this.click();
});
發現有這么一段,可以循環每一個checkbox ,於是我的解決辦法思路就是
剛剛加載頁面的時候手動調用uncheckAll方法,取消所有的checkbox的勾選,然后在獲取下拉框值之前
先判斷下拉框的checkbox是否被選中了,如果被選中了,我才獲取下拉框的值,否則不獲取值。
var isSelect = false; //是否選中。由於調用了uncheckAll,初始為false
$("select").multiselect("widget").find(":checkbox").each(function(){
if ($(this).attr("checked")){
isSelect = true;//真的被選中了。
}
});