I did this with jquery a while back and decided to update it to modern DOM. Allows a set of radio buttons to be deselectable in case such a thing is wanted.
(function () {
let $deselectableInputs = document.querySelectorAll('input[data-deselectable]');
let deselectableLabels = [];
for (let i = 0; i < $deselectableInputs.length; i++) {
// inputs can have multiple labels
// collect them individually to apply their own click events later
let $labels = document.querySelectorAll('label[for="' + $deselectableInputs[i].id + '"]');
for (let j = 0; j < $labels.length; j++) {
deselectableLabels.push($labels[j]);
}
// mouseup event because "click" doesn't work
$deselectableInputs[i].addEventListener('mouseup', function (e) {
if (e.target.checked) {
// delay introduced otherwise false checked doesn't take
window.setTimeout(function () {
e.target.checked = false;
}, 1);
}
});
}
deselectableLabels.forEach(function (item, index) {
// in this case the click event does work
deselectableLabels[index].addEventListener('click', function (e) {
// get relevant input
const $input = e.target.control;
if ($input.checked) {
// still need delay
window.setTimeout(function () {
$input.checked = false;
}, 1);
}
});
});
})();
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.