Last active
February 14, 2020 14:24
-
-
Save rungta/a9db347a9a3a04fabfc1da55296319b7 to your computer and use it in GitHub Desktop.
Make HTML Checkboxes behave like Radio Inputs in that only one can be selected at a time.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(w) { | |
function checkboxAsRadio(selector) { | |
return function (event) { | |
var el = event.target; | |
// only proceed if we have a matching checkbox | |
if (!(el instanceof HTMLInputElement && el.matches(selector))) { | |
return; | |
} | |
// close all open checkboxes with the same name attribute | |
if (el.checked) { | |
Array | |
.from(document.querySelectorAll('input[name=' + el.name + ']')) | |
.filter(function (checkbox) { | |
return checkbox.checked && checkbox !== el; | |
}) | |
.map(function (checkbox) { | |
checkbox.checked = false; | |
}); | |
} | |
}; | |
} | |
document.addEventListener('change', checkboxAsRadio('.checkbox-as-radio')); | |
}(this)); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "checkboxradio", | |
"version": "0.1.1" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment