Try Tuts+ Premium, Get Cash Back!
How to Submit a Form with Control + Enter
videos

How to Submit a Form with Control + Enter

Tutorial Details
  • Topic: JavaScript (jQuery)
  • Difficulty: Easy
  • Estimated Completion Time: 15 minutes

You’ve probably seen it on Twitter, Google+, or Facebook. You’ve got a text box, where you write your status/message and then click a button to submit it. But, if you’re lazy like me, you don’t like to switch to the mouse to click the button. These services help us out by allowing us to press control + enter to submit. Let’s recreate this scenario for our own projects.


Prefer Video?


Of course, the reason we can’t submit on just enter is because we’ll be using a textarea, so that the user can include line breaks. Normally, the browser will just ignore the control key and add another line break when we hit control + enter, but we’ll intercept this and perform our magic.


Step 1: The Template

We’re not here to talk about HTML and CSS so much, so here’s the “template” we start with:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Text Box Enter</title>
    <style>
      body {
        font: 16px/1.5 helvetica-neue, helvetica, arial, san-serif;
      }
      textarea {
        border: 1px solid #ccc;
        display:block;
        width: 250px;
        height: 100px;
      }
      p {
        border: 1px solid #ccc;
        background: #ececec;
        padding: 10px;
        margin: 10px 0;
        width: 230px;
      }
      button {
        border: 1px solid #ccc;
        background: #ececec;
        -webkit-border-radius: 3px;
        padding: 5px 20px;
        margin-top:10px;
      }
    </style>
</head>
<body>

</body>
</html>

Step 2: The HTML

We need a few element to work with here, so let’s add them:

<textarea id="msg"></textarea>
<button type="submit">Post</button>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>

<script>

</script>

I’m really simplifying this here: we only have a textarea and a button. If this were the real deal, we would want an official form here, that would work and submit your message without JavaScript. We’re also including jQuery and an empty script tag that we will take advantage of next.


Step 3: The JavaScript

We’re going to make this as a jQuery plugin that we’ll call ctrlEnter. Here’s what we start with:

$.fn.ctrlEnter = function (btns, fn) {
  var thiz = $(this); 
      btns = $(btns);

};

We’re taking two parameters. We will call this plugin function on the textarea, so we already have that element. The first parameter is a string of one or more selectors that will be passed to jQuery. These are elements that must have the same functionality when clicked. The second parameter is the function that will be executed when control + enter is pressed. Then, we’re creating variables: the jQueryified textarea and the jQueryified btns.

function performAction (e) {
  fn.call(thiz, e);
}

Next, we create a function that wraps the function we passed in. We do this so that we can make sure the function is called with the textarea element as this within the function. We’re also passing it the event object from the event.

thiz.bind("keydown", function (e) {
  if (e.keyCode === 13 && e.ctrlKey) {
    performAction(e);
    e.preventDefault();
  }
});

btns.bind("click", performAction);

Next, we have the actual event handlers. The first wires a function to the keydown event on the textarea element. e.keyCode === 13 means the enter key is being pressed. If e.ctrlKey is true, that means the user was pressing the control key when the enter key was pressed. If the enter key and control key are both being pressed, we’ll call that performAction function. Then, we’ll call e.preventDefault, which will prevent the newline that the enter key would normally write from happening.

And now, let’s wire up the event handlers to the buttons; we’ll simply take the text, replace all occurances of \n with <br />, put it in a paragraph, and prepend it to the body:

$("#msg").ctrlEnter("button", function () {
  $("<p></p>").append(this.val().replace(/\n/g, "<br />")).prependTo(document.body);
  this.val("");
});

Now, let’s test it:


Conclusion: The End

We’ll that’s your quick tip for the day. Have another method of doing this? Hit the comments!

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://eyesurgeontips.com eye surgeon

    Great !! Easy to understand :)

  • http://leorothe.com/ Leonardo Rothe

    Your solution is quite convoluted. It would be better to detect ctrl+enter and trigger submission on the containing form for the textarea. It provides a more straightforward way to handle user input when finished, whether it happens after a submit button click, or the ctrl+enter shortcut.

    $(“textarea”).live(“keydown”, function(e) {
    if (e.keyCode == 13 && e.ctrlKey) $(this).closest(“form”).submit();
    });

    • http://www.jvsoftware.com/ Javier

      I guess he was going for the post messages without refreshing the page approach.

      • http://pistonsky.com Pistonsky

        Ok, but ajaxing should be done in submit button’s code. So I agree with Leonardo.

    • http://www.barbalex.ch alex

      that’s what did it for me!
      thanks a lot

  • Techeese

    Awesome tutorial thanks

  • http://techbrij.com Brij

    Nice Tut!!!

    thiz should be this in following line:

    thiz.bind(“keydown”, function (e) { …

  • irfan

    very good tutorial.

    is there any demo for it

  • Peter

    Demo or it didn’t happen

  • http://ecustom.ca/ Lucas C

    Nice Desktop background, and good tutorial, thanks Andrew!

  • http://andrewburgess.ca Andrew Burgess
    Author

    Hey guys, thanks for the comments!

    Here’s a demo of the code: http://jsbin.com/ehaluq

  • James

    I prefer the alt + s option myself.

    (Note: Maybe Nettuts should implement the alt + s/ctrl + enter methods)

  • Sk1ppeR

    Actually in Facebook and G+ Ctrl+Enter servers for line break and Enter servers for submit. Useless tutorial :X

    • Tim

      Actually, in Facebook Ctrl+Enter does nothing. Shift+Enter is a link break

  • thomas

    Unfortunately I see this approach of jQuery Plugin Authoring a lot, an it is just awefull.

    Every time you call you plugin, new copies of all function expressions are created and that’s in most cases unnecessary.

    A better approach is to wrap the $.fn.myplugin method in an emediate function, define all yout code on top, maybe as constrcutor. Even this one is a better Solution:

    $.fn.myplugin = (function () {
    // code here, eg,
    MyPluginConstructor (arguments) {
    }
    return function (arguments) {
    // note: this still refers to the jQuery object the plugin was called on
    return.this.each(function () {
    // do stuff, e.g.:
    $(this).data(‘pluginname’, new MyPluginConstructor(params));
    });
    }
    }());

    or even so:

    (function () {
    // code here, eg,
    MyPluginConstructor (arguments) {
    }
    $.fn.myplugin = function (arguments) {
    // note: this still refers to the jQuery object the plugin was called on
    return.this.each(function () {
    // do stuff, e.g.:
    $(this).data(‘pluginname’, new MyPluginConstructor(params));
    });
    }
    }());

  • Eric

    I don’t this this works on Google+ and also not on Facebook. In Facebook, a simple posts the comment.

    In G+, I have to double tab and then return. Which, of course, does nothing other than set focus to the post button and then the return presses the button.

    Andrew, while the code is very good, this tut wasn’t your finest moment. :(

  • Eric

    I don’t this this works on Google+ and also not on Facebook. In Facebook, a simple posts the comment.

    In G+, I have to double tab and then return. Which, of course, does nothing other than set focus to the post button and then the return presses the button.

    Andrew, while the code is very good, this tut wasn’t your finest moment here on tutsplus. :(

    • Eric

      … just like my double post wasn’t.

  • Craig Marshall

    This was a great tutorial. Thanks a lot. I hardly get tutorials to the point. But it’s cool.

  • Poona

    Great video!

    Which Vim theme do you use Andrew?

  • http://andrewburgess.ca Andrew Burgess
    Author

    Thanks for the comments, guys. Of course, you’re all right: neither Google+ nor Twitter uses this. I can honestly say that I thought they did . . . I was on Google+ when I (thought I) saw the feature, but I guess I was completely out of it. Sorry for the confusion, and hope you found the tutorial useful. :)

  • http://www.bluelinemedia.co.uk Simon Jackson

    Nice post, but although it is a nice idea in practice I suspect it would go the same way as Ctrl+Left Click on multiple select boxes in that very few users would ever realise that it would exist and/or use it. We are considering adding a Ctrl+S shortcut to our cms at the moment, but we are under no illusions that anyone other than us (who use it all the time and regularly end up pressing the key combination by accident) will be making much use of it.

  • Alexander Trefz

    I think that Tab followed by Space/Enter is way better, because it is standard behaviour that every form provides, and there is no need to add anything, it is just there. So why not use that?

  • Brandon

    The default behavior when submitting a form is to click enter (whether it was with ajax or not). There is no difference when using ajax. The browser will submit the form when clicking enter if it meets the criteria and a button of type ‘submit’ is found within the form. If you do not want to use a button of type ‘submit’ as your button, you can still hide it, but you get the idea.
    jQuery has already come up with a good way of handling the submit event… using the event.preventDefault()… which of course is a bit buggy between browsers. Core functionality is retained and instead of posting the page causing a page refresh, jQuery captures the event and the user can call which function they like.

    Example:

    $(‘#formId’).submit(function(event){
    event.preventDefault();
    //ajax call here
    });

    Obviously your example was to use ctrl + enter, but as you can see from feedback, that does not submit the form in applications.

  • http://www.a2area.it lxn

    Great tutorial! Grats!

  • http://goInventive.co.uk tomsky

    nice tutorial, thanks for sharing Andrew!

  • http://beben-koben.blogspot.com/ Beben Koben

    2 step for enter!
    hmmm…nice nice

  • http://deloz.net Deloz

    good. thanks for sharing Andrew.

  • w1sh

    Good stuff Andrew. Always love your tuts.

  • http://thedevelopertuts.com Bratu Sebastian

    Interesting. thanks !

  • http://lalala.co.co.co hollafer

    I am a newbie here.

    How can i use this from so when a user pressed ctrl+Enter the post will show up and then will be saved on a database.

    How ’bout live update?

  • http://www.avinashdsouza.me Avinash D’Souza

    Does this work in WordPress?

  • http://www.dev-hq.net/ Joe

    I always wondered how these services do this!
    Thanks a lot!

  • http://www.iwebprovider.com Innovative Web Provider

    Very informative. Thanks for this tutorial and the demo!

  • http://www.facebook.com/mittul.chauhan Mittul Chauhan

    superb .. just superb ..