Today I learned: HTML input checkbox can have an indeterminate state
Posted on
As stated by the Mozilla Developer Network documentation,
"In addition to the checked and unchecked states, there is a third state a checkbox can be in: indeterminate."
In the above, a checkbox refers to the HTML element <input type="checkbox" />
.
Since I had never heard about it before in so many years of being a Web developer, I thought it deserves a bit of spotlight.
Most common use case
In a hierarchical checkboxes structure, the indeterminate
state aims at
communicating, on a parent checkbox, that sub-items/sub-options are being
collected (checked).
Example: The grocery list
In upcoming list representations:
[ ]
represents an unchecked checkbox[-]
represents an undeterminate checkbox[x]
represents a checked checkbox.
The below code block aim at representing the inital state of the list:
[ ] Fruits & veggies
[ ] Apple
[ ] Banana
[ ] Cucumber
[ ] Dairy products
[ ] Butter
[ ] Milk
The below code block aims at representing a new state, e.g:
- "Apple" is checked
- "Fruits & Veggies are being collected".
[-] Fruits & veggies
[ ] Banana
[x] Apple
[ ] Cucumber
[ ] Dairy products
[ ] Butter
[ ] Milk
In the above scenario the user checked the "Apple" item.
In order to communicate the state "Fruits & Veggies are being collected",
the "Fruits & Veggies" checkbox gets assigned an indeterminate
state.
Most browsers render this state using "a horizontal line in the box (it looks
somewhat like a hyphen or minus sign) instead of a check/tick", just as we did
in the above code block.
Technical details and constraints
- This can only be an enhancement, since the assignment of the
indeterminate
state can only be done by Javascript.
There is not such thing as anindeterminate
property on the<input type="checkbox" />
HTML element, in comparison to thechecked
state. inputInstance.indeterminate = true;
is how you set that state in Javascript, whereinputInstance
is an instance of theHTMLInputElement
Javascript object.- At form submission, no data is sent to represent an
indeterminate
checkbox. Indeed, it is as if checkbox was not checked. - Screen readers may consider the
indeterminate
checkbox as not checked.
This is at least the case for Voice Over at the time of writing. - There is an
:indeterminate
CSS pseudo class that can be used to target anindeterminate
checkbox.
However, be wary! Indeed that:indeterminate
used alone would not only match checkboxes, but could also match also<input type="radio">
elements and<progress>
elements.
You can read more about the indeterminate checkboxes on CSS Tricks where they present a bunch of implementations and also another use case: "Rotating among the states".