Created
March 10, 2020 23:03
-
-
Save alystair/ccd628620f21ba66b01b0c90d43524ae to your computer and use it in GitHub Desktop.
Avoid submitting a form and focus next available input in a form on enter key
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
document.addEventListener('keydown', function(){ | |
if (event.keyCode === 13 && event.target.nodeName !== 'TEXTAREA') { | |
let form = event.target.closest('form'); | |
if (form) { | |
event.preventDefault(); | |
let startingNode = event.target.nextElementSibling || event.target.parentElement.nextElementSibling; // will break if final? | |
let foundStart = false; | |
function onlyInputs(node) { | |
if (!foundStart && node !== startingNode) return NodeFilter.FILTER_REJECT; | |
else foundStart = true; | |
if (node.offsetHeight === 0 && node.offsetWidth === 0) return NodeFilter.FILTER_REJECT; | |
// node.querySelector('input, textarea, select'); | |
let found = ['INPUT', 'TEXTAREA', 'SELECT'].includes(node.nodeName) && node.type !== 'hidden'; | |
return found ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT; | |
} | |
let nodeIterator = document.createNodeIterator(form, 1, onlyInputs); | |
nodeIterator.nextNode().focus(); | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment