简体   繁体   English

选中getElementById不能选择多个选项

[英]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.

相关问题 "document.getElementById 不能选择多个元素" - document.getElementById can't select more than one element 检查是否在下拉多项选择中选择了多个选项 - Checking if more than one option is selected in a Dropdown Multiple Select 具有多个选择选项的过滤器页面 - A filter page with more than one select option 当我选择两个或两个以上的选项时,discord.js 多选菜单不能运行多个值代码并且不能回复多个交互 - discord.js multi select menus can't run more than one value code when I selected two or more than two options & can't reply more than one interaction Axios &amp; Cheerio - 不能选择多于一个表格行 - Axios & Cheerio - can't select more than one table row 如何对列表使用多个元素“getElementById("site") 和 getElementById("button")”? - How can use elements "getElementById("site") and getElementById("button")" more than one for lists? 如何在 javascript 中获取多个下拉菜单中的选定选项 - How to fetch selected option in javascript for more than one dropdowns 在多个选项标签(列表/菜单)中设置class =&#39;selected&#39; - set class='selected ' in more than one option tag (list/menu) 无法更改选择中的所选选项 - Can't change selected option in a select 从选择选项下拉列表中计算多个值 - Calculating more than one value from select option dropdown
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM