Jquery 多选下拉列表插件jquery multiselect之如何去掉默认选中项1?

我开始接触这个插件的时候,找了很多中文资料,都和下面这篇文章大同小异。

相关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;//真的被选中了。

}

});