2016-02-25 149 views
0

多选问题:我需要在多选下拉列表中选择默认选项。这里我正在使用Struts2,默认选项来自服务器。在多选下拉列表中选择默认值

的Struts代码:

<select multiple > 
    <s:iterator var="user" value="%{USERS}"> 
     <option <s:if test="%{#approvalStep.isUserSelected(#user.userId) == true}"> selected="selected" </s:if> value="<s:property value="#user.userId"/>" > <s:property value="#user.userName"/></option> 
    </s:iterator> 
</select> 

Struts的代码的结果:

<div id="selectAndRemoveUser"> 
    <select multiple=""> 
     <option selected="selected" value="2000000002007"> aftabalamm7861111111</option> 
     <option selected="selected" value="2000000003015"> aftabalam.m+12</option> 
     <option selected="selected" value="2000000003011"> Aftab</option> 
     <option selected="selected" value="2000000026353"> aftabalam.m+approver1</option> 
    </select> 
</div> 

问题: 当我试图使用jQuery这只是返回来获得所选择的选项第一个选项。如果我手动编辑选择>选项元素(我的意思是重新写入selected = selected使用浏览器检查元素),它工作正常。

jQuery代码:

console.log($("#selectAndRemoveUser").find('select :selected').length); // the result is 1; 

if($("#selectAndRemoveUser").find('select :selected').length > 1) { 
    alert('false'); 
} else { 
    alert('true'); 
} 
+1

https://jsfiddle.net/xaLxkhzx/2/你的代码工作 –

+0

确保您已在挤包'$(文件)。就绪您的js代码( function(){});' – RRK

回答

1
For multiselect dropdown, the name of the select field should be defined as array i.e add 'name[]' at the end of the name attribute. 

**HTML** : 
<div id="selectAndRemoveUser"> 
    <select multiple="" name = "user[]"> 
     <option value="2000000002007"> aftabalamm7861111111</option> 
     <option value="2000000003015"> aftabalam.m+12</option> 
     <option value="2000000003011"> Aftab</option> 
     <option value="2000000026353"> aftabalam.m+approver1</option> 
    </select> 
</div> 

**Jquery** : 

$("select") 
    .change(function() { 
    var str = ""; 
    $("select option:selected").each(function() { 
     str += $(this).text() + " "; 
    }); 
    console.log(str); 
    }) 
    .trigger("change"); 
+0

https://jsfiddle.net/xaLxkhzx/7 try dis – Suni