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>
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
Explanation:
-
Array.from(dnd.options)
: Converts theHTMLOptionsCollection
to an array. -
.filter(option => option.selected)
: Filters the array to include only selected options. -
.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);
});
Explanation:
- Loop through each option in the
select
element. - Use
Array.includes()
to check if the option’s value is in the array of values to select. - Set the
selected
property accordingly.
Browser Compatibility
-
Array.from()
: Supported in modern browsers, not in IE. UseArray.prototype.slice.call()
as a polyfill. -
Array.includes()
: Supported in modern browsers, not in IE. UseArray.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;
Usability Note
Multi-select elements can be unintuitive for users. Consider using checkboxes for better usability in most cases.
Top comments (0)