A multiple-selection list can enforce a maximum number of choices in JavaScript. This example allows up to three colors and restores the previous valid selection if a fourth is attempted.
document.addEventListener("DOMContentLoaded", () => {
const list = document.getElementById("ckb");
const message = document.getElementById("limitMessage");
let previous = [];
const saveSelection = () => {
previous = Array.from(list.options, option => option.selected);
};
list.addEventListener("focus", saveSelection);
list.addEventListener("change", () => {
const selected = list.selectedOptions.length;
if (selected > 3) {
Array.from(list.options).forEach((option, index) => {
option.selected = previous[index] || false;
});
message.textContent = "Select no more than three colors.";
return;
}
message.textContent = `${selected} of 3 selected.`;
saveSelection();
});
saveSelection();
});
The older version attached onclick to every option and counted selected options manually. The updated demo listens once on the select element and uses selectedOptions.length.
The original page also compares listbox limits with checkbox limits: checkbox limit tutorial, checkbox limiting demo, getElementsByName limiting demo, value-based checkbox limit, and the checkbox reference.
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.