Last active
July 20, 2017 14:41
-
-
Save GitSquared/6fae768cb45677d817f3cec5d10a2705 to your computer and use it in GitHub Desktop.
Automatically run the onsubmit="" function of forms when the enter key is pressed on the last input field.
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
$(() => { | |
let update_form_listeners = () => { | |
// Always check that the onsubmit attribute ends by return false; otherwise the page will reload | |
$("form[onsubmit] input:last-of-type").each((index, element) => { | |
if ($(element).parents('form').attr('onsubmit').substr(-13) !== 'return false;') { | |
$(element).parents('form').attr('onsubmit', $(element).parents('form').attr('onsubmit')+'return false;'); | |
} | |
}); | |
$("form[onsubmit] input:last-of-type").keypress((e) => { | |
if (e.keyCode === 13) { | |
$(e.target).parents('form').submit(); | |
} | |
}); | |
}; | |
update_form_listeners(); | |
let observer = new MutationObserver(update_form_listeners); | |
observer.observe(document, { | |
subtree: true, | |
childList: true, | |
attributeFilter: ['form', 'input'] | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment