2

I've seen this question, but my question is different because the other question uses value and jQuery, neither of which I want to use.


It's easier to explain with an example:

const select = document.getElementById('sel');
const indexes = new Set([0, 2, 4]);

Array.prototype.forEach.call(select.options, (opt, i) => {
  opt.selected = indexes.has(i);
});
<select id="sel" multiple size=5>
  <option>one</option>
  <option>two</option>
  <option>three</option>
  <option selected>four</option>
  <option>five</option>
</select>

Is this the most efficient way to set the selected options one, three and five? select.selectedIndex doesn't seem to accept an array, so this is the only way I can think to do it. Using a Set ought to be more efficient than looping through an array, each time using .includes.

Donald Duck
  • 8,409
  • 22
  • 75
  • 99
mpen
  • 272,448
  • 266
  • 850
  • 1,236
  • `selectedOptions` contains a collection of the selected option elements, but it's read-only. I think what you've got may be the best way. – Barmar Nov 02 '17 at 21:57
  • But in your example you're also unselecting the option number four. – Jose Hermosilla Rodrigo Nov 02 '17 at 21:59
  • 1
    I tried few things and using loops seemed about 0.1 ms or more, setting `select.innerHTML` about 0.05 ms, and setting them without loop `select.selectedIndex = 0; select[2].selected = true; select[4].selected = true` about 0.03 ms. Ha! the irony of the marked as duplicate being the most **in**efficient way to multi-select – Slai Nov 02 '17 at 23:02
  • Here is very a similar question about choosing multiple options by value (instead of index): https://stackoverflow.com/questions/16582901/javascript-jquery-set-values-selection-in-a-multiple-select/47086131 – Mariano Desanze Nov 02 '17 at 23:26

1 Answers1

3

Loop your indexes array and update the options matching the indexes.

const select = document.getElementById('sel');
const indexes = [0, 2, 4];
// Clear the default selected
select.selectedIndex = -1;
// Select those indexes you want
for(var idx of indexes){
  select[idx].selected = true
}
<select id="sel" multiple size=5>
  <option>one</option>
  <option>two</option>
  <option>three</option>
  <option selected>four</option>
  <option>five</option>
</select>
Jose Hermosilla Rodrigo
  • 3,513
  • 6
  • 22
  • 38