Set selections in a multiple select element with ES6

Latz
Mar 1, 2021
(Photo by Anthony Martino on Unsplash)

If you’re looking on the web for a solution to programmatically set the selections of a multiple select element in JavaScript you most likely find answers using jQuery, an indexed loop and an if condition, or some other complicated stuff. Modern browsers and ES6 gives you a simple solution in (almost) a single line of code:

HTML:

<select id="selectElement" size="3" multiple>
<option value="oranges">Oranges</option>
<option value="apples">Apples</option>
<option value="cherries">Cherries</option>
</select>

JavaScript:

let selectElement = document.getElementById('selectElement');
let a = ['oranges', 'cherries'];
for (option of selectElement.options) option.selected =
a.includes(option.value);

There you go!

--

--

Latz

Long time WordPress Plugin developer. Nowadays I more often code JavaScript frontends and Chrome extensions. Blog: http://www.elektroelch.net/blog