Reputation: 1098
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.
Upvotes: 3
Views: 4113
Reputation: 35950
Use this:
function SendMsg(e)
{
var message = document.getElementById("TxtMessage");
// Load previous message
if(e.keyCode == 38) { message.value = PreviousMessage; return; }
// Send message on ENTER
if(e.keyCode == 13) {
if(message.value !=null && message.value !="")
{
var json = {"message": message.value};
json = JSON.stringify(json);
ws.send(json);
PreviousMessage = message.value;
message.value = "";
message.focus();
}
else
{
CAlert("Message cannot be empty.", false, true);
}
}
}
Update Why keyDown works and keyPress doesn't?
Note that keydown and keyup provide a code indicating which key is pressed, while keypress indicates which character was entered. For example, a lowercase "a" will be reported as 65 by keydown and keyup, but as 97 by keypress. An uppercase "A" is reported as 65 by all events. Because of this distinction, when catching special keystrokes such as arrow keys, .keydown() or .keyup() is a better choice.
In short, keyPress
event won't fire for arrow keys.
Upvotes: 2
Reputation: 50573
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.
Upvotes: 2