Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set values of multiple select using JavaScript

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".

like image 614
eggandegg Avatar asked Apr 03 '19 02:04

eggandegg


People also ask

How do I set multiple selections?

Definition and Usage Selecting multiple options vary in different operating systems and browsers: For windows: Hold down the control (ctrl) button to select multiple options. For Mac: Hold down the command button to select multiple options.

How do you select multiple elements in JavaScript?

Use the querySelectorAll() method to select elements by multiple ids, e.g. document. querySelectorAll('#box1, #box2, #box3') . The method takes a string containing one or more selectors as a parameter and returns a collection of the matching elements.


1 Answers

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>

like image 168
Dacre Denny Avatar answered Sep 21 '22 23:09

Dacre Denny