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

后端 未结 30 1966
难免孤独
难免孤独 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:50
    event.returnValue = false
    

    Use it when handling the event or in the function your event handler calls.

    It works in Internet Explorer and Opera at least.

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

    This is a solution for all the YUI lovers out there:

    Y.on('keydown', function() {
      if(event.keyCode == 13){
        Y.one("#id_of_button").simulate("click");
      }
    }, '#id_of_textbox');
    

    In this special case I did have better results using YUI for triggering DOM objects that have been injected with button functionality - but this is another story...

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

    One basic trick you can use for this that I haven't seen fully mentioned. If you want to do an ajax action, or some other work on Enter but don't want to actually submit a form you can do this:

    <form onsubmit="Search();" action="javascript:void(0);">
        <input type="text" id="searchCriteria" placeholder="Search Criteria"/>
        <input type="button" onclick="Search();" value="Search" id="searchBtn"/>
    </form>
    

    Setting action="javascript:void(0);" like this is a shortcut for preventing default behavior essentially. In this case a method is called whether you hit enter or click the button and an ajax call is made to load some data.

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

    To trigger a search every time the enter key is pressed, use this:

    $(document).keypress(function(event) {
        var keycode = (event.keyCode ? event.keyCode : event.which);
        if (keycode == '13') {
            $('#btnSearch').click();
        }
    }
    
    0 讨论(0)
  • 2020-11-22 00:56

    Use keypress and event.key === "Enter" with modern JS!

    const textbox = document.getElementById("txtSearch");
    textbox.addEventListener("keypress", function onEvent(event) {
        if (event.key === "Enter") {
            document.getElementById("btnSearch").click();
        }
    });
    

    Mozilla Docs

    Supported Browsers

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

    I have developed custom javascript to achieve this feature by just adding class

    Example: <button type="button" class="ctrl-p">Custom Print</button>

    Here Check it out Fiddle
    -- or --
    check out running example https://stackoverflow.com/a/58010042/6631280

    Note: on current logic, you need to press Ctrl + Enter

    0 讨论(0)
提交回复
热议问题