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

Easy & Elegant solution:

First, pressing Enter inside a textarea does not submit the form unless you have script to make it do that. That’s the behaviour the user expects and I’d recommend against changing it. However, if you must do this, the easiest approach would be to find the script that is making Enter submit the form and change it. The code will have something like

if (evt.keyCode == 13) {
    form.submit();
}

… and you could just change it to

if (evt.keyCode == 13 && !evt.shiftKey) {
    form.submit();
}

On the other hand, if you don’t have access to this code for some reason, you need to do the following to make it work in all major browsers even if the caret is not at the end of the text:

jsFiddle: http://jsfiddle.net/zd3gA/1/

Code:

function pasteIntoInput(el, text) {
    el.focus();
    if (typeof el.selectionStart == "number"
            && typeof el.selectionEnd == "number") {
        var val = el.value;
        var selStart = el.selectionStart;
        el.value = val.slice(0, selStart) + text + val.slice(el.selectionEnd);
        el.selectionEnd = el.selectionStart = selStart + text.length;
    } else if (typeof document.selection != "undefined") {
        var textRange = document.selection.createRange();
        textRange.text = text;
        textRange.collapse(false);
        textRange.select();
    }
}

function handleEnter(evt) {
    if (evt.keyCode == 13 && evt.shiftKey) {
        if (evt.type == "keypress") {
            pasteIntoInput(this, "\n");
        }
        evt.preventDefault();
    }
}

// Handle both keydown and keypress for Opera, which only allows default
// key action to be suppressed in keypress
$("#your_textarea_id").keydown(handleEnter).keypress(handleEnter);

Leave a Comment