Created
March 12, 2020 06:47
-
-
Save alystair/9e637d9328eca12e980073c511ece85d to your computer and use it in GitHub Desktop.
Override enter key on longer forms and move to next input (not quite finished)
This file contains hidden or 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 () { | |
// Prevent enter key from submitting form if they are large | |
if (event.keyCode === 13 && event.target.nodeName !== 'TEXTAREA') { | |
let form = event.target.closest('form'); | |
if (form && form.children.length > 10) { // Only large forms | |
event.preventDefault(); | |
// If only one could just send a simulated tab key event to shift to next active field... | |
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