DEV Community

Cover image for Set selections in a multiple select element with ES6
Latz
Latz

Posted on

3 2

Set selections in a multiple select element with ES6

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>
Enter fullscreen mode Exit fullscreen mode

JavaScript

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

There you go!
(Photo by Anthony Martino on Unsplash)

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay