brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: fieldset disabled switches off every field in a form at once

Web-Development
~/tips/tip-fieldset-disabled-whole-form

const form = document.querySelector("#settings");

Disable a whole group of inputs while a form is being sent, with one attribute.

While a form is submitting, I want people to stop changing fields and clicking the button twice. Setting disabled on every control is tedious; one fieldset around them does it in one go.

<form id="settings">
  <fieldset id="settings-fields">
    <input name="name">
    <select name="theme"></select>
    <button>Save</button>
  </fieldset>
</form>

const form = document.querySelector("#settings");
const fields = document.querySelector("#settings-fields");
form.addEventListener("submit", async (event) => {
  event.preventDefault();
  const data = new FormData(form);
  fields.disabled = true;
  try { await save(data); } finally { fields.disabled = false; }
});

When a fieldset has the disabled attribute, all form controls inside it are disabled too, including buttons. They cannot be focused or changed, and browsers grey them out. In the script I set it during the save and remove it in finally, so a failed request does not leave the form locked.

One exception from MDN: controls inside the fieldset’s first legend stay enabled. That lets you put a checkbox in the legend that switches the rest of the group on or off.

The trap: disabled controls are not included when the form is submitted. That is why the script builds the FormData before disabling. If you disable first and then read the form, the data is empty. Use readonly on single inputs when you want a value sent but not edited.

Further reading: MDN: The fieldset element, MDN: disabled attribute

More Web-Development tips ab -n 200 -c 10 https://example.com/ console.assert(items.length > 0, 'cart is empty', items) document.designMode = "on" function save(item) { Save draft All Web-Development tips (67) All topics

Link