Skip to content

Instantly share code, notes, and snippets.

@Lelectrolux
Last active January 9, 2020 08:13
Show Gist options
  • Save Lelectrolux/61b11852c250005da61955f104a7261b to your computer and use it in GitHub Desktop.
Save Lelectrolux/61b11852c250005da61955f104a7261b to your computer and use it in GitHub Desktop.
Basic requiredwith support in HTML/JavaScript
<form>
  <input name="foo" id="foo">
  <input name="bar" id="bar" requiredwith="foo,baz">
  <input name="baz" id="baz">
</form>

Simply add a comma separated list of ids of inputs.

Hooks into native required support, so as is, it won't display a more specialised error message than the default required one.

Not tested on funky value inputs like date or time

document.addEventListener('blur', function (event) {
let formInputs = Array.from(event.target.form.elements).filter(({tagName}) => ['INPUT', 'TEXTAREA', 'SELECT'])
formInputs.filter(elem => {
return elem.hasAttribute('requiredwith') && `,${elem.getAttribute('requiredwith')},`.includes(`,${event.target.id},`)
})
.forEach(input => {
let ids = input.getAttribute('requiredwith').split(',')
formInputs.filter(({id}) => input.getAttribute('requiredwith').split(',').includes(id)).find(({value}) => value)
? input.setAttribute("required", "")
: input.removeAttribute("required")
})
}, true)
function createSelector(ids) {
return ids.map(id => '#'+id).join(',')
}
function getFormInputs(form, selector) {
return Array.from(form.querySelectorAll(selector))
}
Array.from(document.querySelectorAll("[requiredwith]")).forEach(input => {
let elems = getFormInputs(input.form, createSelector(input.getAttribute('requiredwith').split(",")))
input.form.addEventListener("blur", event => {
if (elems.includes(event.target)) {
elems.find(({ value }) => value)
? input.setAttribute("required", "")
: input.removeAttribute("required");
}
}, true);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment