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

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

    This onchange attempt is close, but misbehaves with respect to browser back then forward (on Safari 4.0.5 and Firefox 3.6.3), so ultimately, I wouldn't recommend it.

    <input type="text" id="txtSearch" onchange="doSomething();" />
    <input type="button" id="btnSearch" value="Search" onclick="doSomething();" />
    
    0 讨论(0)
  • 2020-11-22 00:41

    For modern JS keyCode is deprecated, use key instead

    searchInput.onkeyup = function (e) {
        if (e.key === 'Enter') {
            searchBtn.click();
        }
    }
    
    0 讨论(0)
  • 2020-11-22 00:41

    These day the change event is the way!

    document.getElementById("txtSearch").addEventListener('change',
        () => document.getElementById("btnSearch").click()
    );
    
    0 讨论(0)
  • 2020-11-22 00:42

    In Angular2:

    (keyup.enter)="doSomething()"
    

    If you don't want some visual feedback in the button, it's a good design to not reference the button but rather directly invoke the controller.

    Also, the id isn't needed - another NG2 way of separating between the view and the model.

    0 讨论(0)
  • 2020-11-22 00:43

    Although, I'm pretty sure that as long as there is only one field in the form and one submit button, hitting enter should submit the form, even if there is another form on the page.

    You can then capture the form onsubmit with js and do whatever validation or callbacks you want.

    0 讨论(0)
  • 2020-11-22 00:43

    For jQuery mobile, I had to do:

    $('#id_of_textbox').live("keyup", function(event) {
        if(event.keyCode == '13'){
        $('#id_of_button').click();
        }
    });
    
    0 讨论(0)
提交回复
热议问题