Trigger a button click with JavaScript on the Enter key in a text box

后端 未结 30 1916
难免孤独
难免孤独 2020-11-21 23:53

I have one text input and one button (see below). How can I use JavaScript to trigger the button\'s click event when the Enter key is pressed ins

30条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 00:36

    In jQuery, the following would work:

    $("#id_of_textbox").keyup(function(event) {
        if (event.keyCode === 13) {
            $("#id_of_button").click();
        }
    });
    

    $("#pw").keyup(function(event) {
        if (event.keyCode === 13) {
            $("#myButton").click();
        }
    });
    
    $("#myButton").click(function() {
      alert("Button code executed.");
    });
    
    
    Username:
    Password: 

    Or in plain JavaScript, the following would work:

    document.getElementById("id_of_textbox")
        .addEventListener("keyup", function(event) {
        event.preventDefault();
        if (event.keyCode === 13) {
            document.getElementById("id_of_button").click();
        }
    });
    

    document.getElementById("pw")
        .addEventListener("keyup", function(event) {
        event.preventDefault();
        if (event.keyCode === 13) {
            document.getElementById("myButton").click();
        }
    });
    
    function buttonCode()
    {
      alert("Button code executed.");
    }
    
    
    Username:
    Password: 

提交回复
热议问题