Home >Web Front-end >CSS Tutorial >How Can I Prevent Form Submission on Shift Enter in a Text Area?

How Can I Prevent Form Submission on Shift Enter in a Text Area?

Susan Sarandon
Susan SarandonOriginal
2024-12-05 00:03:12319browse

How Can I Prevent Form Submission on Shift Enter in a Text Area?

Shift Enter in TextArea: Generating a New Line

When users press the Enter key inside a text area, submitting the form is the expected behavior. However, if Shift is pressed in combination with Enter, it's often desirable to move the caret to a new line rather than submit the form.

Solution:

There are two primary solutions to this issue:

1. Modify Existing Code:

If there's an existing script that causes Enter to submit the form, modify it to check for the Shift key. Here's an example:

if (evt.keyCode == 13 && !evt.shiftKey) {
    form.submit();
}

2. Use JavaScript and jQuery:

If you don't have access to the existing code, implement this solution using JavaScript and jQuery:

$("#your_textarea_id").keydown(function(evt) {
    if (evt.keyCode == 13 && evt.shiftKey) {
        pasteIntoInput(this, "\n");
        evt.preventDefault();
    }
}).keypress(function(evt) {
    if (evt.keyCode == 13 && evt.shiftKey) {
        pasteIntoInput(this, "\n");
        evt.preventDefault();
    }
});

This code will insert a newline character (n) into the textarea when Shift Enter is pressed, preventing the form from submitting.

The above is the detailed content of How Can I Prevent Form Submission on Shift Enter in a Text Area?. 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