69

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.

Edward Thomson
  • 74,857
  • 14
  • 158
  • 187
Ingrid
  • 1,011
  • 3
  • 9
  • 13

7 Answers7

55

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();
    }
});
Jakub Adamec
  • 953
  • 16
  • 22
Sergio Cabral
  • 6,490
  • 2
  • 35
  • 37
  • 2
    It's been a long time since I wrote this example. But the reason for return false is to prevent the event propagation (just like it does: e.preventDefault ()). Maybe it's unnecessary, but I do not remember. So testing, – Sergio Cabral Jul 21 '18 at 01:58
  • 3
    Pressing Enter seems to send the form (at least the form is closed) but contents of the textarea are not saved. – msoutopico Oct 29 '19 at 16:28
  • 1
    @SergioCabral using e.preventDefault (); is helpful because after pressing Enter, only JS starts without adding a new line to the textarea. – Jakub Adamec Feb 15 '21 at 07:37
44

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>
Dimitar Nestorov
  • 2,411
  • 24
  • 29
27

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();
        }
    });
});
Anders Arpi
  • 8,277
  • 3
  • 33
  • 49
  • Anders, this works but the message only stays for a second and then dissapears from chat. – Ingrid Jan 19 '12 at 22:34
  • Ok, edited something to fit with my chat and your code works perfectly now, thank you all, you've been most kind! – Ingrid Jan 20 '12 at 01:35
  • 11
    Is good, but is better when change [ if (e.which == 13) { ] to [ if(e.which == 13 && !e.shiftKey) { ] ////// In this way we can type SHIFT+ENTER to new line. – Sergio Cabral Apr 04 '16 at 22:15
  • A big issue with the answer is different (non-romanic) language input such as Chinese or Japanese. There you need to click enter to finalize your input and then enter – Viktor Velev Aug 23 '23 at 14:57
5

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.

Kai Qing
  • 18,793
  • 5
  • 39
  • 57
  • I tried it but doesnt seem to work or i simply don't know how to do it right. do i need to change something from code? ty – Ingrid Jan 19 '12 at 22:37
  • I updated my answer. Sorry, I forgot to add your id to the textarea. – Kai Qing Jan 19 '12 at 22:44
  • Ok, now it had a response, seems like i inserted it correctly but i get a blank page like refresh. – Ingrid Jan 19 '12 at 22:56
  • Anders code seems to be the one for my chat it sends the message but for some reason the message only appears 1 second it chat and that puf vanishes. strange. – Ingrid Jan 19 '12 at 22:57
  • You'll need to update your question with your php code then. Cause if this works then your back end isn't doing its job. – Kai Qing Jan 19 '12 at 22:58
0

To capture Enter key in textarea in TailwindCSS:

              onkeypress={(e)=>{
                if(e.key === "Enter" && !e.shiftKey) {
                  INVOKE_YOUR_FUNCTION();
                }
              }}
Russo
  • 2,186
  • 2
  • 26
  • 42
-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>';
  • 1
    Please consider what you are doing. – Spectric Oct 04 '20 at 21:42
  • While this does submit the form, it also puts a line-feed in the SELECT box in some browsers, which you don't want if the form stays put. To fix, have the function return "false" for Enter, and put "return KP();" in the caller. For similar examples, see https://stackoverflow.com/questions/3059559/restrict-a-character-to-type-in-a-text-box – FloverOwe May 12 '21 at 19:46
-3

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.

Jukka K. Korpela
  • 195,524
  • 37
  • 270
  • 390
  • Yes, i know, it used to be text but it's a problem for a chat where longer posts are made (like in this comment box) , to have just one line. Thank you for taking the time to answer. – Ingrid Jan 19 '12 at 23:12