Skip to content

Instantly share code, notes, and snippets.

@rungta
Last active February 14, 2023 06:53
Show Gist options
  • Save rungta/81f72ca7bdff703aa10d1e59f508e210 to your computer and use it in GitHub Desktop.
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.
// 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