Checkbox Example (Mixed-State)
This example demonstrates using the Checkbox Design Pattern to create a tri-state, or mixed-state, checkbox. In this implementation, the mixed-state checkbox represents the state of a set of standard HTML checkboxes. If none of the checkboxes in the set are checked, the mixed state checkbox is not checked, and if all members of the set are checked, the mixed state checkbox is checked. If the set contains both some checked and unchecked checkboxes, the mixed state checkbox is partially checked. Activating the tri-state checkbox changes the states of the checkboxes in the set.
This example also demonstrates use of fieldset
and Legend
elements for labeling the checkbox group.
Similar examples include:
- Checkbox (Two State): Simple two state checkbox.
Example
Keyboard Support
Key | Function |
---|---|
Tab | Moves keyboard focus among the checkboxes. |
Space |
|
Role, Property, State, and Tabindex Attributes
Role | Attribute | Element | Usage |
---|---|---|---|
checkbox |
div |
|
|
tabindex="0" |
div |
Includes the checkbox in the page tab sequence. | |
aria-controls="[IDREFS]" |
div |
identifies the set of checkboxes controlled by the mixed checkbox. | |
aria-checked="false" |
div |
|
|
aria-checked="true" |
div |
|
|
aria-checked="mixed" |
div |
|
Javascript and CSS Source Code
- CSS: checkbox.css
- Javascript: checkboxMixed.js
- Javascript: controlledCheckbox.js
HTML Source Code
<fieldset>
<legend>
Sandwich Condiments
</legend>
<div role="checkbox"
class="group_checkbox"
aria-checked="mixed"
aria-controls="cond1 cond2 cond3 cond4"
tabindex="0">
All condiments
</div>
<ul class="checkboxes">
<li>
<label>
<input type="checkbox" id="cond1">
Lettuce
</label>
</li>
<li>
<label>
<input type="checkbox"
id="cond2"
checked="">
Tomato
</label>
</li>
<li>
<label>
<input type="checkbox" id="cond3">
Mustard
</label>
</li>
<li>
<label>
<input type="checkbox" id="cond4">
Sprouts
</label>
</li>
</ul>
</fieldset>
<script type="text/javascript">
function checkboxFocus (event) {
event.currentTarget.parentNode.classList.add('focus');
};
function checkboxBlur (event) {
event.currentTarget.parentNode.classList.remove('focus');
};
window.onload = function () {
var i;
var mixed = document.querySelectorAll('[role="checkbox"]');
for (i = 0; i < mixed.length; i++) {
var m = new CheckboxMixed(mixed[i]);
m.init();
}
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
for (i = 0; i < checkboxes.length; i++) {
var cb = checkboxes[i];
cb.addEventListener('focus', checkboxFocus);
cb.addEventListener('blur', checkboxBlur);
}
};
</script>