0

I have a textarea field that submit the information when the user press the enter key. Below is what I have:

$(document)ready(function(){
    $('textarea').on('keypress',function(e){
        var txt;
        txt = $(this).val();

        if(e.which == 13)
        {
            //submit the form
        }

    });
});

What I would like to do is submit information when the user presses only the enter key, and do a hard return when the user presses and holds the control key and press enter. (The above code is working fine) I just do not know how to add the other code for the press and hold option. Please explain answer.

Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
Bryan
  • 258
  • 2
  • 12

2 Answers2

2

You can use e.ctrlKey:

$(document).ready(function(){
    $('textarea').on('keypress',function(e) {
        var txt=$(this).val();

        if(e.which === 13 || e.which === 10) {
            if (e.ctrlKey) {
                // handle ctrl-ret here
            } else {
                //submit the form
            }
        }
  });
});

Related question here: detecting ctrl+tab key press in javascript/jQuery

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979
1

Below is a solution that does exactly what you asked for. The code in the JSfiddle has some CSS to show you it works. When you press Enter it will change the color of the text area (you would replace that with your code for submit) but when you press Shift+Enter, it will create a new line and continue editing.

Cheers :D

http://jsfiddle.net/5Kc2T/1/

$(document).ready(function () {
    $('textarea').on('keypress', function (e) {
        var txt = $(this);

        if (e.which == 13) {
            e.preventDefault();
            if (e.shiftKey === true) {
                txt.val(txt.val() + "\n");
            } else {
                //Submit Code Here
            }
        }
    });
});
  • The OP wants the control key, not the shift key. `event.shiftKey != event.ctrlKey`. – RobG Apr 26 '13 at 03:09
  • Sorry about that, i'm used to using Shift+Return for next line. Even this add comment edit box uses it. a simple text change in the above to e.ctrlKey makes that change possable as you pointed out RobG – Dennis Bartlett Apr 30 '13 at 06:26