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)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️