Enter Key
Make the enterKey on any jQuery object trigger a button or link or form.
by cuth
HTML
<input type="text" class="textbox" />
<div id="context">
<input type="text" class="textbox" />
<a href="javascript:alert('test')" class="button">anchor</a>
</div>
JavaScript
// Submit Web Form on Enter Key
(function (namespace, $) {
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;
};
...