Skip to content

Instantly share code, notes, and snippets.

@rungta
Last active February 14, 2020 14:24
Show Gist options
  • Save rungta/a9db347a9a3a04fabfc1da55296319b7 to your computer and use it in GitHub Desktop.
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.
(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));
{
"name": "checkboxradio",
"version": "0.1.1"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment