none of these answer worked for me, reason is that I had an array in my database containing the previous selection and I wanted the user to see highlighted the same selections he had made the last time before changing them. I am also using React that doesn't like the selected tag.
VM71 react_devtools_backend.js:3973 Warning: Use the `defaultValue` or `value` props on <select> instead of setting `selected` on <option>
Thus I decided to manipulate the docref.options directly. Inside React you have to use a useRef hook to do this, so you will see the .current property where the actual Ref is store. You get this by adding the ref= in your html line with the tag select.
Here is the useEffect code, for those not using React just get the code out of the hook, this code is executed by React every time it renders the component.
useEffect(() => {
if(optionRef?.current!==undefined) { // only do something when optionRef has been assigned a doc reference by React
[...optionRef.current.options]?.filter(option => option.value === optionTypes?.filter(type => type===option.value)[0])?.map(option=> option.selected=true)
// because optionTypes is an array of strings, due to using multiple selection, in my case only one match is possible, thus just convert the first and only string of the resulting array to string with the [0]
// this one liner is all that you need if not using react, I only tested it in React
}
}) // I am making it trigger every time it renders, couldn't make it work when tracking optionRef changes or optionRef.current changes, it wouldn't trigger despite the change of optionRef. To make it work I'd probable have to change a state variable every time that optionRef changes, so I decided to just execute this code for every render
HTML part inside a return in React:
<select
name="optionType"
id="idNumber"
ref={optionRef}
multiple={true}
size={3}
> {/* determines the number of elements that will fit into the selection window*/}
<option value="" disabled hidden>Choose Option</option>
<option value="Option1">Option1</option>
</select>