1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScriptでShift + Enterで送信を実装する

Posted at

JavaScriptでtextareaをShift + Enterで送信する実装

<div>
    <textarea id="question" placeholder="質問を入力してください"></textarea>
    <button id="sendBtn">送信</button>
</div>
document.getElementById("question").addEventListener("keypress", e => {
    if (e.key === "Enter" && e.shiftKey) {
        e.preventDefault();

        const sendButton = document.getElementById("sendBtn");
        if (sendButton) {
            sendButton.click();
        }
    }
});
  • 簡単な説明
    • addEventListener: keypressイベントを監視。
    • e.key === "Enter" && e.shiftKey: EnterキーとShiftキーが同時に押されたかをチェック。
    • e.preventDefault(): デフォルトの改行動作をキャンセル。
    • sendButton.click(): 送信ボタンをクリックと同じ処理を走らせる。

・Shift + EnterではなくCtrl + Enterで送信したい場合は、e.shiftkeye.ctrlKeyにするだけ。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?