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 Element.target.value, 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(e.target.value) + 1 e.target.value = i < states.length ? states[i] : states[0] switch(e.target.value) { case states[0]: e.target.checked = true break case states[1]: e.target.indeterminate = true break default: e.target.checked = false } // Sadly, e.target.value is coerced to string console.log(typeof e.target.value) } document.querySelector('input[type=checkbox]').onclick = tristateHandler 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)