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
Release: 2024-12-06 01:51:09
Original
369 people have browsed it

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

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template