user5685187
user5685187

Reputation:

querySelector on <select> tag with multiple attributes

I want to get an array of values which is selected by <select> tag with multiple attributes by using querySelector, NOT jQuery.

I googled on that, but Google lists only about selecting multiple elements by using querySelector. In my case, I want one select element with multiple attributes.

I gave up searching on that, I just tried to code with this <select> tag.

<select id="bgmSources" className="bgmSelector" multiple="multiple"> 
    <option value="1">test1</option>
    <option value="2">test2</option>
    <option value="3">test3</option>
</select>

In JavaScript, I tried as below, but nothing worked.

const values = document.querySelector("#bgmSources").value;
console.log(values);

const selectedOptions = document.querySelectorAll("#bgmSources option:selected");
selectedOptions.forEach(option => console.log(option));

Is there a way to get the array of selected options in <select> tag with multiple attributes?

Upvotes: 1

Views: 2747

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371203

You can select the children options which are :checked, and then get each of those selected options' values:

bgmSources.onchange = () => {
  const selectedOptionVals = Array.from(
    bgmSources.querySelectorAll(':scope > option:checked'),
    ({ value }) => value
  );
  console.log(selectedOptionVals);
};
<select id="bgmSources" className="bgmSelector" multiple="multiple"> 
    <option value="1">test1</option>
    <option value="2">test2</option>
    <option value="3">test3</option>
</select>

You can't use .value to get a meaningful result for multiple, unfortunately, and you have to use :checked, not :selected.

Upvotes: 1

Related Questions