mpen
mpen

Reputation: 283355

How to set multiple selectedIndexes without jQuery?

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.

Upvotes: 2

Views: 98

Answers (1)

Jose Hermosilla Rodrigo
Jose Hermosilla Rodrigo

Reputation: 3683

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>

Upvotes: 3

Related Questions