Home >Web Front-end >CSS Tutorial >How to Detect 'Shift Enter' and Create New Lines in a Textarea Using jQuery or JavaScript?

How to Detect 'Shift Enter' and Create New Lines in a Textarea Using jQuery or JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-12-06 01:51:09370browse

How to Detect

Detecting "Shift Enter" and Generating New Lines in Textarea with jQuery

In web forms, pressing "Enter" in a textarea typically submits the form. However, you may want to implement a different behavior, such as creating a new line when "Shift Enter" is pressed.

jQuery Solution

$("#textarea_id").on("keydown", function(evt) {
  if (evt.keyCode == 13 && evt.shiftKey) {
    // Insert a newline character
    if (evt.type == "keypress") {
      pasteIntoInput(this, "\n");
    }
    // Prevent form submission
    evt.preventDefault();
  }
});

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

Plain JavaScript Solution

var textarea = document.querySelector("#textarea_id");

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

The above is the detailed content of How to Detect 'Shift Enter' and Create New Lines in a Textarea Using jQuery or JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn