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

后端 未结 30 1958
难免孤独
难免孤独 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条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 00:29

    Since no one has used addEventListener yet, here is my version. Given the elements:

    
    
    

    I would use the following:

    var go = document.getElementById("go");
    var txt = document.getElementById("txt");
    
    txt.addEventListener("keypress", function(event) {
        event.preventDefault();
        if (event.keyCode == 13)
            go.click();
    });
    

    This allows you to change the event type and action separately while keeping the HTML clean.

    Note that it's probably worthwhile to make sure this is outside of a

    because when I enclosed these elements in them pressing Enter submitted the form and reloaded the page. Took me a few blinks to discover.

    Addendum: Thanks to a comment by @ruffin, I've added the missing event handler and a preventDefault to allow this code to (presumably) work inside a form as well. (I will get around to testing this, at which point I will remove the bracketed content.)

提交回复
热议问题