DEV Community

Pacharapol Withayasakpunt
Pacharapol Withayasakpunt

Posted on

2 2

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay