[英]getElementById selected can't select more than one option
I have a function in javascript that should allow me to select more than one option, but it only selects the first one. 我有一个javascript函数,应该允许我选择多个选项,但它只选择第一个。
Javascript: 使用Javascript:
function index(){
var a="${staffindex}".replace("[","");
var b=a.replace("]","");
var index1=b.split(",");
for(var i=0;i<index1.length;i++)
document.getElementById("Staff")[index1[i]].selected=true;
}
HTML: HTML:
<select multiple="multiple" id="Staff" name=staff>
<option value = "1" >option1</option>
<option value = "2" >option2</option>
<option value = "3" >option3</option>
<option value = "4" >option4</option>
<option value = "5" >option5</option>
</select>
index1 is an array of numbers received from a java class. index1是从java类接收的数字数组。
Thanks for any help! 谢谢你的帮助!
你忘了使用options
数组:
document.getElementById("Staff").options[index1[i]].selected=true;
getElementById()
function in javascript selects only one element. javascript中的
getElementById()
函数只选择一个元素。 Here it only selects the <select>
tag since it has the id as Staff
and not its options. 这里它只选择
<select>
标签,因为它的id为Staff
而不是它的选项。 You can however access its options as 但是,您可以访问其选项
getElementById("Staff").options[option_number];
Try this: 尝试这个:
function index(){
var a="${staffindex}".replace("[","");
var b=a.replace("]","");
var index1=b.split(",");
for(var i=0;i<index1.length;i++)
document.getElementById("Staff").options[index1[i]].selected=true;
}
That options
is very neccessary here! 这里的
options
非常必要!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.