How to set values of multiple select using JavaScript
Asked Answered
E

4

10

To set data of an <input> element using JavaScript, we assign the value and name of that element like this:

var form = document.createElement("form");
var element = document.createElement("input"); 
element.value=value;
element.name=name;

In the case of a <select> where the multiple attribute is present, how do I set the value of that select element? For instance, how would I set the value of the myselect element below:

<form method="post" action="/post/" name="myform">
  <select multiple name="myselect" id="myselect">
    <option value="1">option1</option>
    <option value="2">option2</option>
        ...

I tried to set the value by doing this myselect.value=[1,2] however it does not work. After selecting option1 and option2 I expected that it returns [1,2], but it just returns "1".

Edmundoedmunds answered 3/4, 2019 at 2:7 Comment(4)
Your question already have answers here #11821761Procurable
Are you trying to select multiple items at the same time in your menu?Sundstrom
@YongQuan linked question doesn't sound related, I think eggandegg is asking how to set <select>, not get all options or the selected option.Sundstrom
@Procurable No it doesn't.Coffey
G
12

To programmatically set multiple value options on a multi-select, you need to manually add selected attributes to the <option> elements that you want to select.

One approach to this is as follows:

const select = document.getElementById('myselect')
const selectValues = [1, 2];

/* Iterate options of select element */
for (const option of document.querySelectorAll('#myselect option')) {

  /* Parse value to integer */
  const value = Number.parseInt(option.value);

  /* If option value contained in values, set selected attribute */
  if (selectValues.indexOf(value) !== -1) {
    option.setAttribute('selected', 'selected');
  }
  /* Otherwise ensure no selected attribute on option */
  else {
    option.removeAttribute('selected');
  }
}
<select multiple name="myselect" id="myselect">
  <option value="1">option1</option>
  <option value="2">option2</option>
  <option value="3">option3</option>
  <option value="4">option4</option>
</select>

Gambia answered 3/4, 2019 at 2:33 Comment(1)
If you also want it to show as selected in the browser, make sure you also add option.selected = true;.Gynophore
D
7

It works

var element = document.getElementById('selectMultiple');

// Set Values
var values = ["Gold", "Bronze"];
for (var i = 0; i < element.options.length; i++) {
    element.options[i].selected = values.indexOf(element.options[i].value) >= 0;
}

// Get Value
var selectedItens = Array.from(element.selectedOptions)
        .map(option => option.value)


spanSelectedItens.innerHTML = selectedItens
<select name='selectMultiple' id="selectMultiple" multiple>
    <option value="Gold">Gold</option>
    <option value="Silver">Silver</option>
    <option value="Bronze">Bronze</option>
</select>
<br />
Selected: <span id="spanSelectedItens"></span>
Diplostemonous answered 3/4, 2019 at 2:27 Comment(1)
Thanks for contributing! It would improve your answer to explain how your solution works.Sundstrom
B
4

You can access the array of select options through the options property of the select object. Every option has a selected property that you can set.

document.myform.myselect.options[0].selected = true;

You can access the options by value using a query selector:

document.myform.myselect.querySelector("option[value="+value+"]")[0].selected = true;
Balalaika answered 3/4, 2019 at 2:26 Comment(0)
A
1

ES6 method to select option1 and option2:

const select = document.getElementById('myselect');

if (select) {
  Array.from(select.options).map((option) => {
    if (option.value === '1' || option.value === '2') {
      option.selected = true;
    }
  });
}
<select multiple name="myselect" id="myselect">
  <option value="1">option1</option>
  <option value="2">option2</option>
  <option value="3">option3</option>
</select>

Note that we need to do Array.from(select.options) first to convert select.options into an array because select.options returns an HTMLOptionsCollection, which doesn't support the map() method.

Alek answered 5/3, 2023 at 0:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.