Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save julianlam/3528689c6d94badf6087025958b3e0c7 to your computer and use it in GitHub Desktop.
Save julianlam/3528689c6d94badf6087025958b3e0c7 to your computer and use it in GitHub Desktop.
Programmatically getting & setting values of a multiselect (without jQuery) #blog

I came across an interesting problem without a good native browser solution, recently. Usually, browser APIs are so complete that this is a non-issue, but nonetheless...

The specific scenario involved a multiselect:

<select multiple id="mySelect">
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
  <option value="4">Four</option>
</select>

A user can easily select multiple options with the use of the cursor or arrow keys, in conjunction with the ctrl and shift modifiers. The element also satisfies accessibility concerns. Wonderful!

Problem

However, there's no easy way to programmatically get or set the value to this input without jQuery, if you want more than one item selected.

console.log(document.getElementById('mySelect').value);  // returns only one option even if multiple are selected
document.getElementById('mySelect').value = '1';

The above code would select the one value. How do we set two?

Solution

With jQuery, it's fairly simple – you can use .deserialize() (available via plugin): $(formEl).deserialize(values);, although that comes with its own pitfalls and edge cases (mostly regarding checkboxes and truthy values).

With vanilla javascript, it's a little more complicated, but straightforward:

const valuesToSet = ['1', '2'];
const selectEl = document.getElementById('mySelect');
const optionEls = selectEl.querySelectorAll('option');

optionEls.forEach((option) => {
  option.selected = valuesToSet.includes(option.value);
});

Likewise, to retrieve the selected options:

const selectEl = document.getElementById('mySelect');
const optionEls = selectEl.querySelectorAll('option');

const selected = Array.prototype.reduce.call(optionEls, (memo, cur) => {
    if (cur.selected) {
      memo.push(cur.value);
    }

    return memo;
}, []);

Add error handling (in case elements don't exist) as necessary.

Codepen

See the Pen Programmatically setting values of a multiselect by Julian Lam (@mailtodevnull) on CodePen.

<script async src="https://cpwebassets.codepen.io/assets/embed/ei.js"></script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment