I have a following piece of code on a few pages, and I'll need it on even more:
$('.editable-textbox').live('keypress', function(e) {
if (e.keyCode == 13) {
$(this).blur();
return false;
}
return true;
}).live('keyup', function(e) {
if (e.keyCode == 13) {
$(this).blur();
return false;
}
return true;
});
There're a few drawbacks of it:
.editable-textbox class + control is blurredI just wonder: is there a way to refactor it to have something like this:
$('.editable-textbox').supressFormSubmitOnEnter();
with jQuery.
Yes.
$.fn.supressFormSubmitOnEnter = function() {
return this.live('keypress', function(e) {
if (e.keyCode == 13) {
$(this).blur();
return false;
}
return true;
}).live('keyup', function(e) {
if (e.keyCode == 13) {
$(this).blur();
return false;
}
return true;
});
};
You should give the Plugin Authoring Guide a read.
Also, it could be written much terser...
$.fn.supressFormSubmitOnEnter = function() {
return $(document).on('keypress keyup', this, function(e) {
if (e.keyCode == 13) {
$(this).blur();
e.preventDefault();
}
});
};
jsFiddle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With