Disable a HTML form while in-flight using fieldset

Sam Thorogood - Jun 11 '19 - - Dev Community

I'm a big fan of great UIs that properly control your user's ability to interact with your page: such as changing some value during a form submit. We've all seen the "do not change this form until it's done!" messages. 🙄

There's a standard HTML feature which can help you with this, in <fieldset disabled>. First, here's a demo:

Try submitting the form, clicking on one of the blue links (they don't go anywhere, it's just for the demo) and pressing the Tab key. The inputs cannot be focused! 🤯

The Feature

When your browser sees a <fieldset> with its disabled attribute set: e.g., <fieldset disabled>, it will completely disable every <input>, <textarea> and <button> element found within. 🚫📝

This is pretty powerful. Your code might look like:

yourForm.addEventListener('submit', (event) => {
  event.preventDefault();  // disable normal submit

  const body = new FormData(yourForm);
  const p = fetch('/foo', {method: 'POST', body}).then((response) => {
    // ...
  });

  // important bit here
  yourFieldset.disabled = true;
  p.finally(() => {
    // .finally runs even if the fetch fails
    yourFieldset.disabled = false;
  });
});
Enter fullscreen mode Exit fullscreen mode

Other uses for fieldset

The fieldset element also lets you group HTML form elements, including adding a legend(-ary). It's useful for accessibility and as a way to visually style groups. For a simple demo, check out this page on MDN.

Alternatives

Classic alternatives to really simple, powerful features like <fieldset disabled> tend to include:

  • adding a giant element that covers the form so users can't click on it
  • iterating through every <input> and marking it disabled
  • just hiding the form.

And all of these are pretty painful versus <fieldset disabled>. 🤮

Thanks!

If you're curious about controlling user interaction, be sure to read up on the "inert" attribute, which takes <fieldset disabled> one step further, but doesn't have full browser support yet.

11 👋

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player