在多选下拉列表中选择默认值

时间:2016-02-25 07:11:21

标签: javascript jquery html

多选的问题:我需要在多选下拉列表中选择默认选项。这里我使用的是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获取所选选项时它只返回第一个选项。如果我手动编辑选择&gt;选项元素(我的意思是重写所选的=使用浏览器检查元素选择)它工作正常。

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 个答案:

答案 0 :(得分: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");
相关问题