jQuery - keydown / keypress /keyup ENTERKEY detection?

后端 未结 4 1572
眼角桃花
眼角桃花 2020-12-01 20:23

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         


        
相关标签:
4条回答
  • 2020-12-01 20:59

    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.

    0 讨论(0)
  • 2020-12-01 21:08

    JavaScript/jQuery

    $("#entersomething").keyup(function(e){ 
        var code = e.key; // recommended to use e.key, it's normalized across devices and languages
        if(code==="Enter") e.preventDefault();
        if(code===" " || code==="Enter" || code===","|| code===";"){
            $("#displaysomething").html($(this).val());
        } // missing closing if brace
    });
    

    HTML

    <input id="entersomething" type="text" /> <!-- put a type attribute in -->
    <div id="displaysomething"></div>
    
    0 讨论(0)
  • 2020-12-01 21:15

    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")
    
    0 讨论(0)
  • 2020-12-01 21:19

    jQuery Sparkle includes a custom event for this. The source can be seen here: http://github.com/balupton/jquery-sparkle/blob/master/scripts/resources/jquery.events.js

    Here is a demo http://www.balupton.com/sandbox/jquery-sparkle/demo/#event-enter

    0 讨论(0)
提交回复
热议问题