Skip to content

Instantly share code, notes, and snippets.

@GitSquared
Last active July 20, 2017 14:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GitSquared/6fae768cb45677d817f3cec5d10a2705 to your computer and use it in GitHub Desktop.
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.
$(() => {
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