0

I'am trying to retrieve all the selected values from a select element with multiple options but I can only grab the last selected value. HTML

<select class="slds-select" id="select-01" multiple="" onchange={checkedPrio}>
                <template for:each={prioList} for:item="pri">
                    <option class="slds-box" key={pri.Id} value={pri} >{pri}</option>
                </template>
  </select>

JS

checkedPrio(event){
        console.log('selected ' + event.target.value) // returns the last clicked option
console.log('ALLLLL' + this.template.querySelector('select.slds-select').value); //this returns the last clicked item as well when I need to grab all the selected ones.

enter image description here

2 Answers 2

2

You can read the options directly from the element:

let selected = [...event.target.options].filter(
  (option)=>option.selected
).map(
  (option)=>option.value
);

This also means you don't have to query the DOM at all, just use the information you're already given.

Demo.

1
  • Thank you, that worked like a charm.
    – kkJhn
    Sep 26, 2022 at 20:18
1

you want to avoid having to query the DOM to get selected values, instead, try updating a property within an array, or adding selected values to an array in your controller, and fetch the values from there instead of doing template.queryselector's

1
  • I don't think they understood why they would only get the first value; querySelector can only return at most one element.
    – sfdcfox
    Sep 26, 2022 at 19:46

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .