devnull.land

Miscellaneous bits and bobs from the tech world

Programmatically getting & setting values of a multiselect (without jQuery)

2/15/2022, 9:36:00 AM


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.