Skeeterfromdoug
Skeeterfromdoug

Reputation: 11

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. 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.

I've tried removing the option tag: var array = $("#elementID").toArray(); using different operators within the option tag: 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);
    })

Upvotes: 0

Views: 45

Answers (1)

Skeeterfromdoug
Skeeterfromdoug

Reputation: 11

Removing :selected worked as desired and allowed for all options in the select element to be successfully passed into the array. The line now looks like:

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

Upvotes: 1

Related Questions