TIMEX TIMEX - 4 years ago 157
Javascript Question

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:


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

Answer Source

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: Caret position in 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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download