Home >Web Front-end >CSS Tutorial >How to Detect 'Shift Enter' and Create New Lines in a Textarea Using jQuery or JavaScript?
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!