Detect the Enter key in a text input field

后端 未结 10 710
粉色の甜心
粉色の甜心 2020-11-29 16:20

I\'m trying to do a function if enter is pressed while on specific input.

What I\'m I doing wrong?

$(document).keyup(function (e) {
    if ($(\".inpu         


        
相关标签:
10条回答
  • 2020-11-29 17:03

    event.key === "Enter"

    More recent and much cleaner: use event.key. No more arbitrary number codes!

    NOTE: The old properties (.keyCode and .which) are Deprecated.

    const node = document.getElementsByClassName("input")[0];
    node.addEventListener("keyup", function(event) {
        if (event.key === "Enter") {
            // Do work
        }
    });
    

    Modern style, with lambda and destructuring

    node.addEventListener('keyup', ({key}) => {
        if (key === "Enter") return false
    })
    

    If you must use jQuery:

    $(document).keyup(function(event) {
        if ($(".input1").is(":focus") && event.key == "Enter") {
            // Do work
        }
    });
    

    Mozilla Docs

    Supported Browsers

    0 讨论(0)
  • 2020-11-29 17:09

    Try this to detect the Enter key pressed in a textbox.

    $(document).on("keypress", "input", function(e){
        if(e.which == 13){
            alert("Enter key pressed");
        }
    });
    

    DEMO

    0 讨论(0)
  • 2020-11-29 17:10

    It may be too late to answer this question. But the following code simply prevents the enter key. Just copy and paste should work.

            <script type="text/javascript"> 
            function stopRKey(evt) { 
              var evt = (evt) ? evt : ((event) ? event : null); 
              var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null); 
              if ((evt.keyCode == 13) && (node.type=="text"))  {return false;} 
            } 
    
            document.onkeypress = stopRKey; 
    
            </script>
    
    0 讨论(0)
  • 2020-11-29 17:10
     $(document).ready(function () {
            $(".input1").keyup(function (e) {
                if (e.keyCode == 13) {
                    // Do something
                }
            });
        });
    
    0 讨论(0)
提交回复
热议问题