How do you make an HTML <select> dropdown behave as read-only in a form? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you make an HTML <select> dropdown behave as read-only in a form?

message-square
0

HTML does not provide a native readonly attribute on <select> elements (unlike <input> or <textarea>), so to make a <select> dropdown behave as read-only in a form, combine visual/interaction locking (aria-readonly="true", tabindex="-1", and pointer-events: none on a read-only visual wrapper/class)—or store/restore the locked value via a Map and event guard—while keeping the <select> enabled (not disabled) so its name and value are still submitted with the form, and wrap DOM/event guards in typeof / instanceof checks and try / catch blocks.


1. Locking a <select> Value While Keeping It Submittable in Forms

Unlike disabled (which prevents the browser from sending the <select> field in form submissions and removes it from tabbing), locking a <select> via value restoration + pointer-events / keyboard guard preserves form submission (FormData, serializeArray(), native submit) while preventing user changes:

<!-- HTML: Keep <select> enabled for form submission, mark aria-readonly, and lock via JS -->
<select id="country-select" name="country" aria-readonly="true" class="is-readonly-select">
  <option value="PK">Pakistan</option>
  <option value="AE">United Arab Emirates</option>
  <option value="GB">United Kingdom</option>
</select>

/* CSS: Prevent pointer interaction while preserving readable styling */
.is-readonly-select {
  pointer-events: none;
  background-color: #f3f4f6;
  opacity: 0.9;
}

// Enforce read-only behavior on an HTMLSelectElement while preserving form submission
function applySelectReadOnlyLock(selectElement, lockedValue, locksMap = new Map()) {
  if (!(selectElement instanceof HTMLSelectElement)) {
    throw new TypeError("Expected selectElement to be an HTMLSelectElement.");
  }
  if (typeof lockedValue !== "string") {
    throw new TypeError("Expected lockedValue to be a string.");
  }
  if (!(locksMap instanceof Map)) {
    throw new TypeError("Expected locksMap to be a Map instance.");
  }

  try {
    // Ensure disabled is false so the field remains a successful form control on submit
    selectElement.disabled = false;
    selectElement.setAttribute("aria-readonly", "true");
    selectElement.classList.add("is-readonly-select");

    const targetOptionExists = Array.from(selectElement.options).some(
      (option) => option.value === lockedValue
    );
    if (!targetOptionExists) {
      throw new RangeError(`Option with value "${lockedValue}" does not exist in <select>.`);
    }

    selectElement.value = lockedValue;
    locksMap.set(selectElement, lockedValue);

    const enforceLockedValue = () => {
      const expected = locksMap.get(selectElement);
      if (typeof expected === "string" && selectElement.value !== expected) {
        selectElement.value = expected;
      }
    };

    const blockKeySelection = (event) => {
      if (!(event instanceof KeyboardEvent)) {
        return;
      }
      const blockedKeys = ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "Space", " "];
      if (blockedKeys.includes(event.key)) {
        event.preventDefault();
      }
    };

    selectElement.addEventListener("change", enforceLockedValue);
    selectElement.addEventListener("input", enforceLockedValue);
    selectElement.addEventListener("keydown", blockKeySelection);

    return () => {
      selectElement.removeEventListener("change", enforceLockedValue);
      selectElement.removeEventListener("input", enforceLockedValue);
      selectElement.removeEventListener("keydown", blockKeySelection);
      selectElement.classList.remove("is-readonly-select");
      selectElement.removeAttribute("aria-readonly");
      locksMap.delete(selectElement);
    };
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    throw new Error(`Failed locking <select> as read-only: ${message}`);
  }
}

// Example usage:
// try {
//   const countrySelect = document.querySelector("#country-select");
//   const lockRegistry = new Map();
//   const unlockCountry = applySelectReadOnlyLock(countrySelect, "PK", lockRegistry);
//   // Call unlockCountry() later if the field becomes editable again
// } catch (error) {
//   console.error(`${error.name}:${error.message}`);
// }
  • Do not use disabled if you need the <select> submitted with the form: Disabled form controls are omitted from native form submission and FormData.
  • Restore selectElement.value on change/input: Blocks programmatic or keyboard/accessibility changes that bypass pointer-events: none.

2. Alternative Pattern: disabled <select> + Hidden <input type="hidden">

When you want native browser disabled semantics (greyed-out control, skipped in tab order, no dropdown popup) and still need the value submitted in standard HTML forms, pair a disabled <select> (without a name attribute) with a synced <input type="hidden" name="..."> tracked in a Map:

// Sync a disabled <select> with a hidden <input> so the locked value still submits
function syncDisabledSelectWithHiddenInput(selectElement, hiddenInputElement, syncMap = new Map()) {
  if (!(selectElement instanceof HTMLSelectElement)) {
    throw new TypeError("Expected selectElement to be an HTMLSelectElement.");
  }
  if (!(hiddenInputElement instanceof HTMLInputElement)) {
    throw new TypeError("Expected hiddenInputElement to be an HTMLInputElement.");
  }
  if (!(syncMap instanceof Map)) {
    throw new TypeError("Expected syncMap to be a Map instance.");
  }

  try {
    selectElement.disabled = true;
    selectElement.setAttribute("aria-readonly", "true");
    hiddenInputElement.type = "hidden";
    hiddenInputElement.value = selectElement.value;

    syncMap.set(selectElement, hiddenInputElement);
    return selectElement.value;
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    throw new Error(`Failed syncing disabled <select> with hidden input: ${message}`);
  }
}

// Example usage:
// try {
//   const sel = document.querySelector("#tier-select");
//   const hid = document.querySelector("#tier-hidden");
//   const pairs = new Map();
//   syncDisabledSelectWithHiddenInput(sel, hid, pairs);
// } catch (error) {
//   console.error(`${error.name}:${error.message}`);
// }
  • Remove name from the disabled <select> (or keep name only on the hidden <input>): Avoids confusion and keeps form payload serialization explicit.
  • Use Map to link control pairs: Avoids attaching custom ad-hoc properties directly onto DOM nodes.

3. Accessibility, Form Submission, and Security Caveats

Keep these read-only <select> considerations in mind in production forms:

  • Client-side read-only locks are UI/UX guards, not security boundaries: Always re-validate locked/immutable fields (such as account plan, assigned role, or currency) on the server when processing form submissions.
  • Test screen-reader and keyboard behavior: Screen readers announce disabled controls differently than aria-readonly="true" controls; verify how assistive tech and keyboard navigation behave in your target UI.
  • Always validate option values before locking: Assigning a value that does not match any <option value="..."> leaves <select>.value empty ("") on non-matching controls.