DEV Community

Avnish
Avnish

Posted on

Get all selected values of a multiple Select field in JS

Working with Multi-Select Elements in Vanilla JavaScript

HTML Example

Here’s a multi-select example:

<label for="dnd">What are the best classes in D&D?</label>
<select id="dnd" multiple>
    <option value="bard">Bard</option>
    <option value="fighter">Fighter</option>
    <option value="druid">Druid</option>
    <option value="paladin">Paladin</option>
    <option value="rogue">Rogue</option>
    <option value="wizard">Wizard</option>
</select>
Enter fullscreen mode Exit fullscreen mode

Getting All Selected Values

To retrieve all selected values from this multi-select, we need to loop through its options and filter out the selected ones.

Here’s how to do it:

// Get the select element
var dnd = document.querySelector('#dnd');

// Get all selected values
var selectedValues = Array.from(dnd.options) // Convert options to an array
    .filter(option => option.selected)      // Filter selected options
    .map(option => option.value);           // Map to an array of values

console.log(selectedValues); // Logs the selected values
Enter fullscreen mode Exit fullscreen mode

Explanation:

  1. Array.from(dnd.options): Converts the HTMLOptionsCollection to an array.
  2. .filter(option => option.selected): Filters the array to include only selected options.
  3. .map(option => option.value): Maps the selected options to their values.

Setting Selected Values

To set specific values in a multi-select, use an array of values and update the selected property of each option.

// Array of values to select
var valuesToSelect = ['bard', 'wizard'];

// Update the selected options
Array.from(dnd.options).forEach(option => {
    option.selected = valuesToSelect.includes(option.value);
});
Enter fullscreen mode Exit fullscreen mode

Explanation:

  1. Loop through each option in the select element.
  2. Use Array.includes() to check if the option’s value is in the array of values to select.
  3. Set the selected property accordingly.

Browser Compatibility

  • Array.from(): Supported in modern browsers, not in IE. Use Array.prototype.slice.call() as a polyfill.
  • Array.includes(): Supported in modern browsers, not in IE. Use Array.indexOf() as a fallback.

Polyfill Example:

// Polyfill for Array.from
var optionsArray = Array.prototype.slice.call(dnd.options);

// Polyfill for Array.includes
var isSelected = selected.indexOf(option.value) > -1;
Enter fullscreen mode Exit fullscreen mode

Usability Note

Multi-select elements can be unintuitive for users. Consider using checkboxes for better usability in most cases.

Top comments (0)