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.

5
  • 1
    What programming language are you talking about? HTML?
    – gorootde
    Jan 19, 2012 at 22:09
  • Php is the programming language.
    – Ingrid
    Jan 19, 2012 at 22:14
  • 1
    Maybe because if you type too long text in <input type="text">, text won't wrap like in textarea. Jan 19, 2012 at 22:16
  • 1
    programming language should be irrelevant here since this is a client side request.
    – Kai Qing
    Jan 19, 2012 at 22:16
  • Um..I'll go read about textbox and see what this is about. Thank you.
    – Ingrid
    Jan 19, 2012 at 22:17

7 Answers 7

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();
    }
});
3
  • 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, Jul 21, 2018 at 1: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, 2019 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. Feb 15, 2021 at 7: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>

6
  • please note, that new Event() will not work in IE11
    – pttsky
    Apr 28, 2019 at 19:53
  • @pttsky added a note about IE 11 Apr 29, 2019 at 18:08
  • 9
    Thumb up for vanilla. Who wants jQuery anyways?
    – Calsal
    Sep 30, 2019 at 13:00
  • The keypress event is deprecated. Use keydown instead. developer.mozilla.org/en-US/docs/Web/API/Element/keypress_event
    – ericek111
    Jan 10 at 18:34
  • event.target.form.requestSubmit(); is cleaner than dispatchEvent. All modern browsers support it, as of Safari 16.
    – mfluehr
    Mar 1 at 21:03
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();
        }
    });
});
4
  • Anders, this works but the message only stays for a second and then dissapears from chat.
    – Ingrid
    Jan 19, 2012 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, 2012 at 1: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. Apr 4, 2016 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 Aug 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.

5
  • 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, 2012 at 22:37
  • I updated my answer. Sorry, I forgot to add your id to the textarea.
    – Kai Qing
    Jan 19, 2012 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, 2012 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, 2012 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, 2012 at 22:58
0

To capture Enter key in textarea in TailwindCSS:

              onkeypress={(e)=>{
                if(e.key === "Enter" && !e.shiftKey) {
                  INVOKE_YOUR_FUNCTION();
                }
              }}
-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>';
2
  • 1
    Please consider what you are doing.
    – Spectric
    Oct 4, 2020 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 stackoverflow.com/questions/3059559/…
    – FloverOwe
    May 12, 2021 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.

1
  • 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, 2012 at 23:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.