Categories
JavaScript Answers

How to select multiple options with JavaScript?

Spread the love

Sometimes, we want to select multiple options with JavaScript.

In this article, we’ll look at how to select multiple options with JavaScript.

How to select multiple options with JavaScript?

To select multiple options with JavaScript, we can set the selected property of the option we want to select to true.

For instance, we write:

<select multiple>
  <option value="1">One</option>
  <option value="2">two</option>
  <option value="3">three</option>
</select>

to add a multi-select element.

Then we write:

const select = document.querySelector('select')
for (const o of select.options) {
  if (+o.value < 3) {
    o.selected = true
  }
}

to select the select element with querySelector.

Then we loop through the options in the element with the for-of loop.

We get the options with select.options.

And if o.value is less than 3, we set o.selected to true.

Therefore, the first 2 choices are selected since their value attributes have value less than 3 when converted to a number.

Conclusion

To select multiple options with JavaScript, we can set the selected property of the option we want to select to true.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *