How to Submit a Form with Control + Enter

http://net.tutsplus.com/tutorials/javascript-ajax/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:

  1. <!DOCTYPE html>  
  2. <html lang="en">  
  3. <head>  
  4.     <meta charset="UTF-8" />  
  5.     <title>Text Box Enter</title>  
  6.     <style>  
  7.       body {  
  8.         font: 16px/1.5 helvetica-neue, helvetica, arial, san-serif;  
  9.       }  
  10.       textarea {  
  11.         border: 1px solid #ccc;  
  12.         display:block;  
  13.         width: 250px;  
  14.         height: 100px;  
  15.       }  
  16.       p {  
  17.         border: 1px solid #ccc;  
  18.         background: #ececec;  
  19.         padding: 10px;  
  20.         margin: 10px 0;  
  21.         width: 230px;  
  22.       }  
  23.       button {  
  24.         border: 1px solid #ccc;  
  25.         background: #ececec;  
  26.         -webkit-border-radius: 3px;  
  27.         padding: 5px 20px;  
  28.         margin-top:10px;  
  29.       }  
  30.     </style>  
  31. </head>  
  32. <body>  
  33.   
  34. </body>  
  35. </html>  

Step 2: The HTML

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

  1. <textarea id="msg"></textarea>  
  2. <button type="submit">Post</button>  
  3.   
  4. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>  
  5.   
  6. <script>  
  7.   
  8. </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:

  1. $.fn.ctrlEnter = function (btns, fn) {  
  2.   var thiz = $(this);   
  3.       btns = $(btns);  
  4.   
  5. };  

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 textareaand the jQueryified btns.

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

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.

  1. thiz.bind("keydown"function (e) {  
  2.   if (e.keyCode === 13 && e.ctrlKey) {  
  3.     performAction(e);  
  4.     e.preventDefault();  
  5.   }  
  6. });  
  7.   
  8. btns.bind("click", performAction);  

Next, we have the actual event handlers. The first wires a function to the keydown event on the textareaelement. 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:

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

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!





  • superb .. just superb ..

    • Avatar
      Innovative Web Provider    a year ago

      Very informative. Thanks for this tutorial and the demo!

      • Avatar
        Joe    2 years ago

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

        • Avatar
          Avinash D'Souza    2 years ago

          Does this work in WordPress?

          • Avatar
            hollafer    2 years ago

            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?

          • Avatar
            Bratu Sebastian    2 years ago

            Interesting. thanks !

            • Avatar
              w1sh    2 years ago

              Good stuff Andrew. Always love your tuts.

              • Avatar
                Deloz    2 years ago

                good. thanks for sharing Andrew.

                • Avatar
                  Beben Koben    2 years ago

                  2 step for enter!
                  hmmm...nice nice

                  • Avatar
                    tomsky    2 years ago

                    nice tutorial, thanks for sharing Andrew!

                    • Avatar
                      lxn    2 years ago

                      Great tutorial! Grats!

                      • Avatar
                        Brandon    2 years ago

                        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.

                        • Avatar
                          Alexander Trefz    2 years ago

                          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?

                          • Avatar
                            Simon Jackson    2 years ago

                            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.

                            • Avatar
                              Andrew Burgess    2 years ago

                              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. :)

                              • Avatar
                                Poona    2 years ago

                                Great video!

                                Which Vim theme do you use Andrew?

                              • Avatar
                                Craig Marshall    2 years ago

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

                                • Avatar
                                  Eric    2 years ago

                                  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. :(

                                • Avatar
                                  Eric    2 years ago

                                  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. :(

                                  • Avatar
                                    thomas    2 years ago

                                    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));
                                    });
                                    }
                                    }());

                                    see more
                                    • Avatar
                                      Sk1ppeR    2 years ago

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

                                    • Avatar
                                      James    2 years ago

                                      I prefer the alt + s option myself.

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

                                      • Avatar
                                        Andrew Burgess    2 years ago

                                        Hey guys, thanks for the comments!

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

                                        • Avatar
                                          Lucas C    2 years ago

                                          Nice Desktop background, and good tutorial, thanks Andrew!

                                          • Avatar
                                            Peter    2 years ago

                                            Demo or it didn't happen

                                            • Avatar
                                              irfan    2 years ago

                                              very good tutorial.

                                              is there any demo for it

                                              • Avatar
                                                Brij    2 years ago

                                                Nice Tut!!!

                                                thiz should be this in following line:

                                                thiz.bind("keydown", function (e) { ...

                                                • Avatar
                                                  Techeese    2 years ago

                                                  Awesome tutorial thanks

                                                  • Avatar
                                                    Leonardo Rothe    2 years ago

                                                    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();
                                                    });

                                                  • Avatar
                                                    eye surgeon    2 years ago

                                                    Great !! Easy to understand :)





                                                  • superb .. just superb ..

                                                    • Avatar
                                                      Innovative Web Provider    a year ago

                                                      Very informative. Thanks for this tutorial and the demo!

                                                      • Avatar
                                                        Joe    2 years ago

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

                                                        • Avatar
                                                          Avinash D'Souza    2 years ago

                                                          Does this work in WordPress?

                                                          • Avatar
                                                            hollafer    2 years ago

                                                            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?

                                                          • Avatar
                                                            Bratu Sebastian    2 years ago

                                                            Interesting. thanks !

                                                            • Avatar
                                                              w1sh    2 years ago

                                                              Good stuff Andrew. Always love your tuts.

                                                              • Avatar
                                                                Deloz    2 years ago

                                                                good. thanks for sharing Andrew.

                                                                • Avatar
                                                                  Beben Koben    2 years ago

                                                                  2 step for enter!
                                                                  hmmm...nice nice

                                                                  • Avatar
                                                                    tomsky    2 years ago

                                                                    nice tutorial, thanks for sharing Andrew!

                                                                    • Avatar
                                                                      lxn    2 years ago

                                                                      Great tutorial! Grats!

                                                                      • Avatar
                                                                        Brandon    2 years ago

                                                                        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.

                                                                        • Avatar
                                                                          Alexander Trefz    2 years ago

                                                                          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?

                                                                          • Avatar
                                                                            Simon Jackson    2 years ago

                                                                            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.

                                                                            • Avatar
                                                                              Andrew Burgess    2 years ago

                                                                              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. :)

                                                                              • Avatar
                                                                                Poona    2 years ago

                                                                                Great video!

                                                                                Which Vim theme do you use Andrew?

                                                                              • Avatar
                                                                                Craig Marshall    2 years ago

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

                                                                                • Avatar
                                                                                  Eric    2 years ago

                                                                                  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. :(

                                                                                • Avatar
                                                                                  Eric    2 years ago

                                                                                  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. :(

                                                                                  • Avatar
                                                                                    thomas    2 years ago

                                                                                    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));
                                                                                    });
                                                                                    }
                                                                                    }());

                                                                                    see more
                                                                                    • Avatar
                                                                                      Sk1ppeR    2 years ago

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

                                                                                    • Avatar
                                                                                      James    2 years ago

                                                                                      I prefer the alt + s option myself.

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

                                                                                      • Avatar
                                                                                        Andrew Burgess    2 years ago

                                                                                        Hey guys, thanks for the comments!

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

                                                                                        • Avatar
                                                                                          Lucas C    2 years ago

                                                                                          Nice Desktop background, and good tutorial, thanks Andrew!

                                                                                          • Avatar
                                                                                            Peter    2 years ago

                                                                                            Demo or it didn't happen

                                                                                            • Avatar
                                                                                              irfan    2 years ago

                                                                                              very good tutorial.

                                                                                              is there any demo for it

                                                                                              • Avatar
                                                                                                Brij    2 years ago

                                                                                                Nice Tut!!!

                                                                                                thiz should be this in following line:

                                                                                                thiz.bind("keydown", function (e) { ...

                                                                                                • Avatar
                                                                                                  Techeese    2 years ago

                                                                                                  Awesome tutorial thanks

                                                                                                  • Avatar
                                                                                                    Leonardo Rothe    2 years ago

                                                                                                    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();
                                                                                                    });

                                                                                                  • Avatar
                                                                                                    eye surgeon    2 years ago

                                                                                                    Great !! Easy to understand :)

                                                                                                  • 0
                                                                                                    点赞
                                                                                                  • 0
                                                                                                    收藏
                                                                                                    觉得还不错? 一键收藏
                                                                                                  • 0
                                                                                                    评论

                                                                                                  “相关推荐”对你有帮助么?

                                                                                                  • 非常没帮助
                                                                                                  • 没帮助
                                                                                                  • 一般
                                                                                                  • 有帮助
                                                                                                  • 非常有帮助
                                                                                                  提交
                                                                                                  评论
                                                                                                  添加红包

                                                                                                  请填写红包祝福语或标题

                                                                                                  红包个数最小为10个

                                                                                                  红包金额最低5元

                                                                                                  当前余额3.43前往充值 >
                                                                                                  需支付:10.00
                                                                                                  成就一亿技术人!
                                                                                                  领取后你会自动成为博主和红包主的粉丝 规则
                                                                                                  hope_wisdom
                                                                                                  发出的红包
                                                                                                  实付
                                                                                                  使用余额支付
                                                                                                  点击重新获取
                                                                                                  扫码支付
                                                                                                  钱包余额 0

                                                                                                  抵扣说明:

                                                                                                  1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
                                                                                                  2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

                                                                                                  余额充值