DEV Community

Pacharapol Withayasakpunt
Pacharapol Withayasakpunt

Posted on

Clickable tristate checkbox

There is HTMLButtonElement.indeterminate, but you cannot set it normally on click.

This one is quite simple. You need two things.

  • JavaScript onclick handler
  • Place to hold the state

A simple implementation for this, is to store on, however, it can only be strings (otherwise, it will be coerced to string).

function tristateHandler(e) {
  const states = ['true', 'null', 'false']

  const i = states.indexOf( + 1 = i < states.length ? states[i] : states[0]
  switch( {
    case states[0]: = true
    case states[1]: = true
    default: = false

  // Sadly, is coerced to string

document.querySelector('input[type=checkbox]').onclick = tristateHandler
Enter fullscreen mode Exit fullscreen mode

Top comments (0)