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;
});
});
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 itdisabled
- 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 ๐
Top comments (6)
I usually just do
pointer-events: none
in CSS, that does the trick.The tab key or alternative methods of access can trivially get "under" your block.
Sure, makes sense. But to me itโs mostly a style-thing, yโknow? I check for repeated request with a nonce and stuff anyway, so if someone is uncles to really try to to that, I donโt care.
Unless, it might be bad for accessibility, now that I think of it :-/
Oh good. I mean you're dealing with a repeat submission issue your way, and that's greatโthat's the actual problem I want to help readers solveโbut maybe do consider accessibility.
e.g. What happens if I use 'enter' to submit the form (which I find really awkward anyway) or 'space' if I'm focused on the button. I probably still have focus and could submit again.
Surprising to know this
*Le me do not know any HTML now ๐
Nice post ๐
Very cool! Thanks ๐๐ฝ