Javascript 如何使用数组提供的值设置列表框中选择的项目?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7762544/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to set the items selected in a listbox with values provided by an array?
提问by GLP
In my apsx page, I have a listbox (techGroups) that has some items that are preselected. The user can change the selections. Meanwhile, I have a reset button. When the user click the reset button, the listbox will be restored with those preselected items selected, while others are not.
在我的 apsx 页面中,我有一个列表框 (techGroups),其中包含一些预选的项目。用户可以更改选择。同时,我有一个重置按钮。当用户单击重置按钮时,列表框将恢复为选中的那些预选项目,而其他项目则不会。
I write following javascript function for the reset button's onclientclick. Somehow, after i click the reset button, only the first preselected item get selected, all other preselected items are not.
我为重置按钮的 onclientclick 编写了以下 javascript 函数。不知何故,在我点击重置按钮后,只有第一个预选项目被选中,所有其他预选项目都没有被选中。
reset()
{
var selectedGroups = hiddenfield1.value.split(","); //i saved those preselected items in a hiddenfield
for (var i = 0; i < techGroups.options.length; i++) {
for (var j = 0; j < selectedGroups.length; j++) {
if (techGroups.options[i].value == selectedGroups[j]) {
techGroups.options[i].selected = true;
}
}
}
}
Can anybody help me to look at my code and tell me what is wrong? Thanks.
谁能帮我看看我的代码并告诉我出了什么问题?谢谢。
采纳答案by adatapost
May be reference issue (DOM). Try this,
可能是参考问题(DOM)。尝试这个,
JavaScript:
JavaScript:
<script type="text/javascript">
window.onload = function () {
var btnReset = document.getElementById("btnReset");
btnReset.onclick = function () {
var hid1 = document.getElementById("hiddenField1");
var techGroups = document.getElementById("techGroups");
var selectedGroups = hid1.value.split(","); //i saved those preselected items in a hiddenfield
for (var i = 0; i < techGroups.options.length; i++) {
for (var j = 0; j < selectedGroups.length; j++) {
if (techGroups.options[i].value == selectedGroups[j]) {
techGroups.options[i].selected = true;
}
}
}
};
};
</script>
Markup:
标记:
<form id="form1" runat="server">
<div>
<input type="hidden" id="hiddenField1" value="aa,bb,cc" />
<select id="techGroups" size="4" multiple="multiple">
<option value="rr">rr</option>
<option value="aa">aa</option>
<option value="cc">cc</option>
<option value="zz">zz</option>
<option value="bb">bb</option>
<option value="dd">dd</option>
</select>
<input type="button" id="btnReset" value="Reset" />
</div>
</form>
回答by Renato Gama
jQuery allowed? if so please see it working here (if not, please disconsider):
jQuery 允许吗?如果是这样,请在这里查看它(如果不是,请不要考虑):