When dealing with form elements that feature multiple selections, a common task involves extracting the selected values. This is particularly relevant for scenarios where you need to capture the preferences or choices of a user.
JavaScript Technique for Extracting Selected Values
To retrieve the selected values from a
<code class="javascript">function getSelectValues(select) { var values = []; for (var i = 0; i < select.options.length; i++) { if (select.options[i].selected) { values.push(select.options[i].value || select.options[i].text); } } return values; }</code>
This function iterates through the
Example Usage
Consider the following HTML markup:
<code class="html"><select multiple> <option>Option 1</option> <option value="Option 2">Option 2</option> </select> <button onclick=" var select = document.querySelector('select'); var values = getSelectValues(select); alert(values); "> Show Selected Values </button></code>
When the button is clicked, the getSelectValues function is invoked and the selected values are displayed in an alert box.
Additional Considerations
The JavaScript method outlined above offers a reliable way to retrieve selected values from multiple select boxes. However, it's worth noting that in certain circumstances, you may encounter cross-browser compatibility issues with the value and text properties. To ensure consistent behavior, consider using a library like jQuery if browser compatibility is a major concern.
The above is the detailed content of How to Retrieve Selected Values From a Multiple Select Element in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!