Reputation: 17773
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.
Upvotes: 3
Views: 562
Reputation: 490333
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();
}
});
};
Upvotes: 7