Home > Net >  I want a radio button that unchecks when clicked (javascript)
I want a radio button that unchecks when clicked (javascript)

Time:03-06

I have a website that currently has a lot of radio buttons. Just recently, I have decided I would prefer behaviour that's a combination of radio and checkbox. So if you click on a checked box, it unchecks (like a checkbox), but if you click on an unchecked box, the clicked box checks and all other boxes uncheck (like a radio button).

An extremely similar question has been asked and answered here How to check/uncheck radio button on click? however the answer was written in jquery and I'm trying to keep everything in javascript.

I could just play around until I find something that works, but that technique usually gets me things that only work on one browser, so I'm hoping for a bit more of an "industry standard" answer that works for all browsers past and future (as much as possible).

The ideal solution would let me keep the markup as radio buttons, because I'm working with code I wrote when I was still learning, and my CSS is a mess.

But a non-ideal solution is still better than no solution.

The buttons are already using an onclick function for something else, so it's probably best to leverage that, or is it?

CodePudding user response:

Just handle the onclick event to un-check the value, usually by setting to null or undefined. Even if there is current logic in the click handler, in that logic too would you would probably want to reverse whatever is going on in the click.

The problem with un-selection of a radio group is that you have to clear the selection value, depending on your framework you might have other logic that depends on 1 value being selected.

I generally solve this UI conundrum by deliberately adding a radio button that mapps to the undefined state, then you can use validation (if you need it) to ensure that by the end of the form the user does select a value. This additional option makes the management of the state simpler to code but also gives the user explicit control. A magic javascript firing (perhaps after an unexpected delay) after you accidentally double clicked on a radio button or re-selected the same value is not the usual interaction and will likely cause a number of users to submit without a selection, even though they fully intented to select an option.

We should exercise caution when trying to manipulate controls to perform non-standard behaviours. There is a reason that we have standards and that it is hard to do what you are trying to do. Find a solution that uses the controls the way they were designed... Refer to the principal of "least astonishment" to keep your users happy.

  • Related