A <select multiple> can have several selected options at the same time. The modern selectedOptions collection avoids scanning every option when all you need is the current selection.
const list = document.getElementById("s1");
const values = Array.from(list.selectedOptions, option => option.value);
Demo of reading multiple selections
<select id="s1" name="months[]" multiple size="6">
<option value="Jan">January</option>
<option value="Feb">February</option>
<option value="Mar">March</option>
</select>
The size attribute controls how many rows are visible. The array-style name is useful when a server processes multiple submitted values.
function readSelected() {
return Array.from(s1.selectedOptions, option => option.value);
}
The original page demonstrated the underlying logic by looping through every option and checking its selected property. That approach is still valid when you also need to inspect unselected options.
const values = [];
for (const option of s1.options) {
if (option.selected) {
values.push(option.value);
}
}
This connects with the original lessons on array length and if conditions, and with the HTML guide to multiple select lists.
For plain text output, join the values and assign the result to textContent. This avoids constructing HTML from option values.
output.textContent = values.length ? values.join(", ") : "No selection";
Continue with limiting multiple listbox selections when the user may choose several options but only up to a fixed maximum.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.