gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:35:48 25 4
gpt4 key购买 nike

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

最佳答案

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");

关于javascript - 在多选下拉列表中选择默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35620644/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com