How do I detect “shift+enter” and generate a new line in Textarea?

Currently, if the person presses enter inside the text area, the form will submit.
Good, I want that.

But when they type shift + enter, I want the textarea to move to the next line: n

How can I do that in JQuery or plain JavaScript as simple as possible?


Better use simpler solution:

Tim’s solution below is better I suggest using that:

My solution

I think you can do something like this..

EDIT : Changed the code to work irrespective of the caret postion

First part of the code is to get the caret position.

Ref: How to get the caret column (not pixels) position in a textarea, in characters, from the start?

function getCaret(el) { 
    if (el.selectionStart) { 
        return el.selectionStart; 
    } else if (document.selection) { 
        var r = document.selection.createRange(); 
        if (r == null) { 
            return 0;
        var re = el.createTextRange(), rc = re.duplicate();
        rc.setEndPoint('EndToStart', re);
        return rc.text.length;
    return 0; 

And then replacing the textarea value accordingly when Shift + Enter together , submit the form if Enter is pressed alone.

$('textarea').keyup(function (event) {
    if (event.keyCode == 13) {
        var content = this.value;  
        var caret = getCaret(this);          
            this.value = content.substring(0, caret - 1) + "n" + content.substring(caret, content.length);
        } else {
            this.value = content.substring(0, caret - 1) + content.substring(caret, content.length);

Here is a demo

Leave a Reply

Your email address will not be published. Required fields are marked *