I had the same problem and understood this. None of the answers above work exactly the way I wanted - most of them require an additional button to reset the radio. The goal was to turn off the radio by clicking on the radio itself.
Here's the fiddle: http://jsfiddle.net/MEk5Q/1/
The problem was very complicated, because the value of the switch changes before the click event fires, so when we listen to the event, we cannot determine whether the switch was already set or not. In both cases, it has already been verified. Another approach was to listen to the mousedown event. Unlike click , it starts before changing the radio checked attribute, but deleting it inside the event handler does not give us anything, since it is checked again during the mouseup event.
My answer is a bit ugly workaround, so I usually donβt offer it to others, and I probably will refuse it myself. It works , but it includes a 20 ms timeout function, which I do not like in such cases.
Here is the code explanation:
$('input[type="radio"]').on('mousedown', function() { if (this.checked) { //on mousedown we can easily determine if the radio is already checked this.dataset.check = '1'; //if so, we set a custom attribute (in DOM it would be data-check="1") } }).on('mouseup', function() { if (this.dataset.check) { //then on mouseup we determine if the radio was just meant to be unchecked var radio = this; setTimeout(function() {radio.checked = false;}, 20); //we give it a 20ms delay because radio checking fires right after mouseup event delete this.dataset.check; //get rid of our custom attribute } });
As a timeout function, I could use a string (less record), but as far as I know, it will be eval 'ed. Although I do not trust the eval function, I prefer the anonymous function.
One more thing - one may ask, why is spreading the code to two separate event handlers, while we can run the timeout function on mousedown? Well, what if someone clicks the mouse on the radio and holds it for a few seconds or even someone is just a very slow person;). Typically, with this solution, we omit the lag problem between mousedown and mouseup .
If you need more information about dataset , here is the MDN link: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.dataset This property comes with HTML5 and may not be cross-server, therefore, if you want 100% compatibility, replace it with any other solution that will contain data, you name it.
Sorry for jQuery here and there, but I hope everything is fine with it - it was a lot easier.
I hope you will like it.