Skip to content

Instantly share code, notes, and snippets.

@cuth
Last active December 30, 2015 12:09
Show Gist options
  • Select an option

  • Save cuth/7827001 to your computer and use it in GitHub Desktop.

Select an option

Save cuth/7827001 to your computer and use it in GitHub Desktop.
Add enter key submission to web forms.
// Submit Web Form on Enter Key
(function (exports, $) {
var submitAnchor = function (anchor) {
if (anchor.onclick) {
if (!anchor.onclick()) return;
}
var href = $(anchor).attr('href');
if (href.indexOf('javascript') >= 0) {
eval(unescape(href.replace(/^javascript:/i,"")));
}
else {
window.location = href;
}
},
submitInput = function (input) {
input.click();
},
submitForm = function (form) {
form.submit();
},
submit = function () {
var self = this;
this.$submit.each(function () {
if (this.tagName == 'A') {
submitAnchor.call(self, this);
return;
}
if (this.tagName == 'INPUT' || this.tagName == 'BUTTON') {
submitInput.call(self, this);
return;
}
if (this.tagName == 'FORM') {
submitForm.call(self, this);
return;
}
});
},
bindEvents = function () {
var self = this;
this.$input.on('keypress', function (e) {
if (e.which == 13) {
e.preventDefault();
submit.call(self);
}
});
},
init = function (input, submit, context) {
this.$context = $(context);
if (this.$context.length) {
this.$input = this.$context.find(input);
this.$submit = this.$context.find(submit);
} else {
this.$input = $(input);
this.$submit = $(submit);
}
if (!this.$input.length || !this.$submit.length) return false;
bindEvents.call(this);
return true;
};
exports.WebFormEnter = function (input, submit, context) {
this.result = init.call(this, input, submit, context);
};
}(this, jQuery));
@cuth
Copy link
Copy Markdown
Author

cuth commented Dec 6, 2013

To use, run this code.

new WebFormEnter('#form .text', '#submitButton');

@cuth
Copy link
Copy Markdown
Author

cuth commented Dec 6, 2013

Fiddle with it here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment