3

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:

  • the code doesn't imply what it does. What it does is: prevents form submittion when enter is hit on control with .editable-textbox class + control is blurred
  • of course code duplication

I just wonder: is there a way to refactor it to have something like this:

$('.editable-textbox').supressFormSubmitOnEnter();

with jQuery.

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

-1

You've got a great resource in the jQuery Docs

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.