Ingrid
Ingrid

Reputation: 1091

How to make "Enter" key in a textarea submit a form

I have a chat that uses textarea instead of text for obvious reasons. This is why each time members hit ENTER they get a new line instead of sending the message. I would like to change this, so every time they hit ENTER =the message to be submitted and then the cursor to return on textarea for their next message typing. I've tried different codes found on this site, most didnt work and those who seemed to do something were just refreshing the page and i got a blank page.

My code:

<form name="message" action="">
    <textarea name="usermsg" autocomplete="off" type="text" id="usermsg" rows="4" cols="30" style="width: 450px; margin-left: 25px;">
    </textarea>
    <br/>

    <p style="margin-left: 420px;"><input name="submitmsg" type="submit"  id="submitmsg" value="Send" /></p>
</form>

Thank you very much for your time.

Upvotes: 77

Views: 103938

Answers (7)

Sergio Cabral
Sergio Cabral

Reputation: 7006

Try this (note that pressing Enter submits, and Shift+Enter adds a new line).

$("#textareaId").keypress(function (e) {
    if(e.which === 13 && !e.shiftKey) {
        e.preventDefault();
    
        $(this).closest("form").submit();
    }
});

EDIT 1: At the time, I wrote the above code using jQuery. For vanilla JavaScript, use the code below which accomplishes the same thing.

document.getElementById("textareaId").addEventListener("keypress", e => {
    if (e.key === "Enter" && !e.shiftKey) {
        e.preventDefault();

        e.currentTarget.closest("form").submit();
    }
});

Upvotes: 60

Russo
Russo

Reputation: 3082

To capture Enter key in textarea in TailwindCSS:

              onkeypress={(e)=>{
                if(e.key === "Enter" && !e.shiftKey) {
                  INVOKE_YOUR_FUNCTION();
                }
              }}

Upvotes: 0

Dimitar Nestorov
Dimitar Nestorov

Reputation: 2604

Vanilla JavaScript solution

function submitOnEnter(event) {
    if (event.which === 13) {
        if (!event.repeat) {
            const newEvent = new Event("submit", {cancelable: true});
            event.target.form.dispatchEvent(newEvent);
        }

        event.preventDefault(); // Prevents the addition of a new line in the text field
    }
}

document.getElementById("usermsg").addEventListener("keydown", submitOnEnter);

If you would prefer to add a new line when Shift is held all you need to do is change line 2 to:

if (event.which === 13 && !event.shiftKey) {

To clear the textarea just add this after the dispatchEvent line:

event.target.value = "";

To use this with Internet Explorer 11 change line 4 and 5 to:

var newEvent = document.createEvent("Event");
newEvent.initEvent("submit", false, true);
event.target.form.dispatchEvent(newEvent);

But wait? Why not use event.target.form.submit();?

When you invoke the submit method of the form the event listeners will not be called.


function submitOnEnter(event) {
    if (event.which === 13) {
        if (!event.repeat) {
            const newEvent = new Event("submit", {cancelable: true});
            event.target.form.dispatchEvent(newEvent);
        }

        event.preventDefault(); // Prevents the addition of a new line in the text field
    }
}

document.getElementById("usermsg").addEventListener("keydown", submitOnEnter);

document.getElementById("form").addEventListener("submit", (event) => {
    event.preventDefault();
    console.log("form submitted");
});
<form id="form">
    <textarea id="usermsg"></textarea>
    <button type="Submit">Submit</button>
</form>

Upvotes: 49

Eric Dienot
Eric Dienot

Reputation: 1

function KP()
{    
var x = event.keyCode;
   if(x==13)
        {
            // alert (x);
            document.message.submit();
        }
}

php

echo '<textarea  name="usrMsg" id="usrMsg" OnKeyPress="KP();">'txt'</textarea>';

Upvotes: -2

Kai Qing
Kai Qing

Reputation: 18843

Well, supposing you were using jquery it would be a simple listener on your input field:

In your footer before </body>:

<script type="text/javascript">
$(document).ready(function(){
    $('#usermsg').keypress(function(e){
      if(e.which == 13){
           // submit via ajax or
           $('form').submit();
       }
    });
});
</script>

In your html head add this:

<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js" type="text/javascript" charset="utf-8"></script> 

but if js or jquery is out of the question then perhaps update your question to specifically exclude it.

Upvotes: 5

Jukka K. Korpela
Jukka K. Korpela

Reputation: 201836

Use <input type=text> instead of <textarea>. Then you have much better chances. In textarea, hitting Enter is supposed to mean a line break in text, not submission of text.

Upvotes: -4

Anders Arpi
Anders Arpi

Reputation: 8417

I have created a jsfiddle with an example on how to do it with jQuery and the keypressfunction and which property: http://jsfiddle.net/GcdUE/

Not sure exactly what you are asking for more than this, so please specify your question further if possible.

$(function() {
    $("#usermsg").keypress(function (e) {
        if(e.which == 13) {
            //submit form via ajax, this is not JS but server side scripting so not showing here
            $("#chatbox").append($(this).val() + "<br/>");
            $(this).val("");
            e.preventDefault();
        }
    });
});

Upvotes: 27

Related Questions