Last active
February 14, 2023 06:53
-
-
Save rungta/81f72ca7bdff703aa10d1e59f508e210 to your computer and use it in GitHub Desktop.
HTML validation polyfill for checkboxes to require at least one option with the same input name.
This file contains 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
// Allow 'require-ing' at least one option from a list of checkboxes | |
// with the same name. Polyfill for modifying the default HTML behaviour | |
// which is requiring all checkboxes with the 'required' attribute | |
// | |
// eg: | |
// <input type=checkbox name=eg value=a data-required-any> | |
// <input type=checkbox name=eg value=b data-required-any> | |
// <input type=checkbox name=eg value=c data-required-any> | |
(function (window) { | |
'use strict'; | |
function checkboxFixRequired(event) { | |
var el = event.target; | |
var selector = 'input[type=checkbox][data-required-any]'; | |
// only proceed if we have a matching checkbox | |
if (!(el instanceof HTMLInputElement && el.matches(selector))) { | |
return; | |
} | |
// disable 'required' on all unselected checkboxes with the same name attribute | |
// when one is checked, otherwise enable 'required' | |
Array.from( | |
el.form.querySelectorAll( | |
selector + | |
'[name="' + el.name + '"]' + | |
':not(:checked)' | |
) | |
).map(function (checkbox) { | |
checkbox.required = !el.checked; | |
}); | |
} | |
document.addEventListener('change', checkboxFixRequired); | |
}(this)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment