15

Possible Duplicate:
Bind textbox to 'enter' key

I've made a chat system with AJAX and jQuery and there is no <form> tag wrapping the TextBox for chat messages, so I can't submit that message with the ENTER button on the keyboard.

Is there any way I can submit that value from TextBox with javascript?

Thanks.

harisdev
  • 4,146
  • 5
  • 19
  • 25

3 Answers3

35
document.getElementById("id_of_your_textbox").addEventListener("keydown", function(e) {
    if (!e) { var e = window.event; }
    e.preventDefault(); // sometimes useful

    // Enter is pressed
    if (e.keyCode == 13) { submitFunction(); }
}, false);
  • 1
    if you're using a function to do something else like I was remember to throw an e.preventDefault(); in before the function call to prevent the form being submitted. – DShook Dec 17 '12 at 17:59
  • The original prevents me from typing anything into the box, edited to make it work proper. – grepsedawk Mar 25 '14 at 20:04
13
$('#textboxId').keydown(function (event) {
    let keyPressed = event.keyCode || event.which;
    if (keyPressed === 13) {
        $(this).closest('form').submit();
    }
});

If you don't have form, then replace $(this).closest('form').submit(); with whatever AJAX/submit logic you have.

Community
  • 1
  • 1
nachito
  • 6,975
  • 2
  • 25
  • 44
0

You will need to listen for the ENTER key press event. Take a look at Enter key press event in JavaScript for some examples on how it is done.

Community
  • 1
  • 1
moranjk
  • 151
  • 1
  • 5