[jquery] jQuery - keydown / keypress /keyup ENTERKEY detection?

Trying to get jQuery to detect enter input, but space and other keys are detected, enter isn't detected. What's wrong below:

$("#entersomething").keyup(function(e) {
    alert("up");
    var code = (e.keyCode ? e.keyCode : e.which);
    if (code==13) {
        e.preventDefault();
    }

    if (code == 32 || code == 13 || code == 188 || code == 186) {
        $("#displaysomething").html($(this).val());
});

<input id="entersomething" />
<div id="displaysomething"&gt;&lt;/div&gt;

http://jsfiddle.net/zeRrv/

This question is related to jquery

The answer is



I think you'll struggle with keyup event - as it first triggers keypress - and you won't be able to stop the propagation of the second one if you want to exclude the Enter Key.


update: nowadays we have mobile and custom keyboards and we cannot continue trusting these arbitrary key codes such as 13 and 186. in other words, stop using event.which/event.keyCode and start using event.key:

if (event.key === "Enter" || event.key === "ArrowUp" || event.key === "ArrowDown")