2

I need to send form input to js function after keypress enter

Following answer https://stackoverflow.com/a/905233/6827096 but below code refreshing page after pressing enter.

#.html
<script src="chat.js'"></script>
<input  onkeypress="return sendChatMessage(event)">

#chat.js
function sendChatMessage(e) {
    if (e.keyCode == 13) {
        console.log("e.keyCode == 13");   //never reachable
        return false;
    }
    return true;
}

How to avoid refreshing page with event onkeypress ENTER (keyCode == 13) ?

Function sendChatMessage is visible in browser console with page loaded.

Community
  • 1
  • 1
user6827096
  • 1,186
  • 1
  • 11
  • 26

3 Answers3

4

If your input is within <form> element, pressing Enter will try to submit the form. Try to add preventDefault() in your sendChatMessage():

function sendChatMessage(e) {
    if (e.keyCode == 13) {
        e.preventDefault();  // this should prevent default action
        console.log("e.keyCode == 13");   //never reachable
        return false;
    }
    return true;
}
errata
  • 5,695
  • 10
  • 54
  • 99
1

Try adding e.preventDefault(); to your function sendChatMessage, it is going to prevent link from opening. Your code will look like this:

function sendChatMessage(e) {

    if (e.keyCode == 13) {
e.preventDefault();  // add  this line of code.
        console.log("e.keyCode == 13");   //never reachable
        return false;
    }
    return true;
}
haMzox
  • 2,073
  • 1
  • 12
  • 25
1

Try to use both e.which and e.keyCode:

function sendChatMessage(e) {
    if (e.which == 13 || e.keyCode == 13) {
        e.preventDefault();
        console.log("e.keyCode == 13"); 
        return false;
    }
    return true;
}
Taras Kovalenko
  • 2,323
  • 3
  • 24
  • 49