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

后端 未结 30 1904
难免孤独
难免孤独 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:39

    To add a completely plain JavaScript solution that addressed @icedwater's issue with form submission, here's a complete solution with form.

    NOTE: This is for "modern browsers", including IE9+. The IE8 version isn't much more complicated, and can be learned here.


    Fiddle: https://jsfiddle.net/rufwork/gm6h25th/1/

    HTML

    
        

    JavaScript

    // The document.addEventListener replicates $(document).ready() for
    // modern browsers (including IE9+), and is slightly more robust than `onload`.
    // More here: https://stackoverflow.com/a/21814964/1028230
    document.addEventListener("DOMContentLoaded", function() {
        var go = document.getElementById("go"),
            txt = document.getElementById("txt"),
            outige = document.getElementById("outige");
    
        // Note that jQuery handles "empty" selections "for free".
        // Since we're plain JavaScripting it, we need to make sure this DOM exists first.
        if (txt && go)    {
            txt.addEventListener("keypress", function (e) {
                if (event.keyCode === 13)   {
                    go.click();
                    e.preventDefault(); // <<< Most important missing piece from icedwater
                }
            });
    
            go.addEventListener("click", function () {
                if (outige) {
                    outige.innerHTML += "Clicked!
    "; } }); } });

提交回复
热议问题