Obtain Values from a Multiple Select Box Using JavaScript
In scenarios where you encounter a multiple select box, accessing its selected values is essential. This question delves into an effective approach to retrieve these values using JavaScript.
To begin with, the code snippet you provided iterates through the options of the multiple select box, checking if each option is selected. If true, the option's value is added to an array.
An alternative solution is presented below, offering a concise and efficient way to obtain the selected values:
<code class="js">function getSelectValues(select) { // Create an empty array to store the values. const result = []; // Obtain the options from the select element. const options = select && select.options; // Loop through the options to check which ones are selected. for (let i = 0; i < options.length; i++) { const option = options[i]; // If the option is selected, we push its value into the result array. if (option.selected) { result.push(option.value || option.text); } } // Return the populated result array with the selected values. return result; }
This function takes in a select element as an argument and returns an array of selected values. Here's a quick example demonstrating its usage:
<code class="html"><select multiple> <option>Option 1</option> <option value="value-2">Option 2</option> </select> <button onclick=" const selectElement = document.getElementsByTagName('select')[0]; const selectedValues = getSelectValues(selectElement); console.log(selectedValues); ">Show Selected Values</button></code>
The above is the detailed content of How to Get Selected Values from a Multiple Select Box in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!