简体   繁体   English

将 select 元素中的所有项目发送到 JavaScript 数组

[英]Sending all items in a select element to a JavaScript array

I am currently using two select elements and utilizing js buttons to send options back and forth between elements.我目前正在使用两个 select 元素并利用 js 按钮在元素之间来回发送选项。 Users will move options from the left side to the right side and submit the page to make changes to their database.用户会将选项从左侧移动到右侧,然后提交页面以对他们的数据库进行更改。 I am able to move elements back and forth with:我可以通过以下方式来回移动元素:

var array = $("#elementID option:selected").toArray();

without trouble.没有麻烦。

I would like to be able to utilize this same method to send all Select Element options to an array regardless of whether or not they were selected.我希望能够利用相同的方法将所有 Select 元素选项发送到数组,无论它们是否被选中。

I've tried removing the option tag: var array = $("#elementID").toArray();我试过删除选项标签: var array = $("#elementID").toArray(); using different operators within the option tag: var array = $("#elementID option:all").toArray(); var array = $("#elementID option:unselected").toArray();在选项标签中使用不同的运算符: var array = $("#elementID option:all").toArray(); var array = $("#elementID option:unselected").toArray(); var array = $("#elementID option:all").toArray(); var array = $("#elementID option:unselected").toArray(); I am unable to find any documentation for further usage of the option tag outside of "selected" Here is my full button:除了“已选择”之外,我找不到任何进一步使用选项标签的文档这是我的完整按钮:

$("#clearGroup").on("click", function(){
    var allItems = $("#activeGroups option:selected").toArray();
    console.log(allItems);

    var allAvail = document.getElementById("availableGroups");
    var allAct = document.getElementById("activeGroups");
    
    allItems.forEach(function(item){
        //remove Options from right side side
        //activeGroups.remove(activeGroups.selectedIndex);
        //Establish child option and add it to activeGroup Select Element
        var opt = document.createElement('option');
        opt.value = item.value;
        opt.innerHTML = item.text;
        allAvail.appendChild(opt);
        allAct.removeChild(item);
    })

Removing :selected worked as desired and allowed for all options in the select element to be successfully passed into the array.删除:selected按需要工作,并允许将 select 元素中的所有选项成功传递到数组中。 The line now looks like:该行现在看起来像:

var allItems = $("#activeGroups option").toArray();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM