In your scenario, you have a
Utilizing the native getSelectValues function, you can efficiently retrieve an array containing the selected values from the
<code class="javascript">function getSelectValues(select) { var result = []; var options = select && select.options; var opt; for (var i = 0, iLen = options.length; i < iLen; i++) { opt = options[i]; if (opt.selected) { result.push(opt.value || opt.text); } } return result; }</code>
To use this function, simply pass the
<code class="html"><select id="mySelect" multiple> <option>Option 1</option> <option value="value2">Option 2</option> </select></code>
<code class="javascript">var selectedValues = getSelectValues(document.getElementById("mySelect"));</code>
The selectedValues variable will now contain an array of the selected option values. You can then perform any necessary operations on this array.
The above is the detailed content of How to Efficiently Retrieve Selected Values from a Multi-Select Element in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!