Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript up arrow keypress not firing

I've been doing some JS recently and getting this stupid error, I can detect the return key using e.keyCode and checking for keyCode == 13 but when I try to check for 38 (Up arrow) it never fires. Any help please?

HTML:

<input type="text" id="TxtMessage" 
       placeholder="Message" onKeyPress="SendMsg(event)" >

Javascript:

function SendMsg(e)
{
var message = document.getElementById("TxtMessage");

if(e.keyCode ==13)
{
    var json = {"message": message.value};
    json = JSON.stringify(json);
    ws.send(json);
    PreviousMessage = message.value;
    message.value = "";
    message.focus();
}
else if(e.keyCode == 38) 
{ 
    message.value = PreviousMessage;
}
}

EDIT: Fixed by changing onKeyPress to onKeyDown... Strange.

like image 202
user1763295 Avatar asked Feb 26 '26 20:02

user1763295


1 Answers

Replace your following lines:

if(e.keyCode !=13) return;
if(e.keyCode == 38) { message.value = PreviousMessage; return;  }

for this one:

var charCode = typeof e.which == "number" ? e.which : e.keyCode;

if(charCode == 38) { message.value = PreviousMessage; return;  }
if(charCode !=13) return;

UPDATE:
My above code still didn't work when used in keypress event, as the correct solution is to use keydown or keyup events to catch the arrow keys. See here for an enhanced answer https://stackoverflow.com/a/2218915/352672 Also see here a working jsfiddle using the keyup event.

like image 154
Nelson Avatar answered Feb 28 '26 11:02

Nelson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!