indeterminate Marks Tri-State Checkboxes

Keep a select-all checkbox truthful: indeterminate marks partial selection while checked stays binary, and aria-checked mixed exposes the third state.

JavascriptForm Validation

Code

javascriptsnippet
33 lines
// 三态全选:全选 / 全不选 / 部分选中
const list = document.createElement('ul');
const rows = ['README.md', 'notes.txt', 'todo.md'];
const checks = rows.map((name) => {
  const label = document.createElement('label');
  const box = document.createElement('input');
  box.type = 'checkbox';
  box.className = 'row-check';
  label.append(box, document.createTextNode(name));
  list.append(label);
  return box;
});

const selectAll = document.createElement('input');
selectAll.type = 'checkbox';
selectAll.setAttribute('aria-label', 'Select all');

function syncSelectAll() {
  const checked = checks.filter((box) => box.checked).length;
  // checked 只有两种取值;indeterminate 单独表达"部分选中"
  selectAll.checked = checked === checks.length;
  selectAll.indeterminate = checked > 0 && checked < checks.length;
  // 读屏器靠 aria-checked="mixed" 感知第三种状态
  selectAll.setAttribute('aria-checked', selectAll.indeterminate ? 'mixed' : String(selectAll.checked));
}

selectAll.addEventListener('change', () => {
  for (const box of checks) box.checked = selectAll.checked;
  syncSelectAll();
});
for (const box of checks) box.addEventListener('change', syncSelectAll);
document.body.append(selectAll, list);
syncSelectAll();

indeterminate Marks Tri-State Checkboxes: how the code works

The whole flow routes through syncSelectAll.

The core work runs in nested loops — outer for (const box of checks) box.checked = selectAll.checked;, inner for (const box of checks) box.addEventListener('change', syncSelectAll);.

Points of care

  • The import surface (if any) is all standard library, all versioned with the language itself.
  • The snippet leans on document — browser-only surfaces a bare Node process cannot provide.

Using it

Entry signature: function syncSelectAll()

Key statements

selectAll.addEventListener('change', () => {
  for (const box of checks) box.checked = selectAll.checked;
  syncSelectAll();
});
for (const box of checks) box.addEventListener('change', syncSelectAll);
const checked = checks.filter((box) => box.checked).length;

Interactive Tools for This Topic

FAQ

Does indeterminate Marks Tri-State Checkboxes run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.