Limit Multiple Listbox Selections with JavaScript

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.

0 of 3 selected.
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.

Restricting number of user selections from Dropdown listbox multi option in JavaScript

Related checkbox limits

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.

Limiting number of selection user can check from a group of checkboxes by using JavaScript

Listbox




Subscribe to our YouTube Channel here



plus2net.com










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer