Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
635 views
in Technique[技术] by (71.8m points)

html - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();
    }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...