I have this select
with the multiple
option enabled:
<div class="col-md-6">
<label for="weekday" class="form-label">Weekday</label>
<select name="weekday" id="weekday" class="form-select" size="7" multiple aria-label="Weekday">
<option value="0">Sunday</option>
<option value="1">Monday</option>
<option value="2">Tuesday</option>
<option value="3">Wednesday</option>
<option value="4">Thursday</option>
<option value="5">Friday</option>
<option value="6">Saturday</option>
</select>
</div>
Before enabling the multiple
option, I was able to programmatically select an item in this way:
document.querySelector("#weekday").value = "5"
I cannot understand the right syntax to select multiple items via Javascript.
Here and here I find nothing useful.
Say I want to select 0
, 2
and 4
. How should I change the above call?
3
Answers
You can select option using
querySelector
then you can easily addselected
attribute.To select and set the selected indexes, you can use the .selectedIndexes() method. This method takes an array of indexes as its argument.
In your case, you want to select the indexes 0, 2, and 4. So, you would use the following code:
This code will select the indexes 0, 2, and 4 in the select element with the id "weekday".
You can use
document.querySelector
to get each wanted option and set theselected
property to true for each one.