How do I detect "shift+enter" and generate a new line in Textarea? Ask Question

How do I detect

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?

ベストアンサー1

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

一方、何らかの理由でこのコードにアクセスできない場合は、キャレットがテキストの末尾にない場合でも、すべての主要ブラウザで動作するようにするには、次の操作を行う必要があります。

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

コード:

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

おすすめ記事