How to trigger HTML button when you press Enter in textbox?

后端 未结 12 1249
悲哀的现实
悲哀的现实 2020-12-04 08:13

So the code that I have so far is:

&
相关标签:
12条回答
  • 2020-12-04 08:48

    I found w3schools.com howto, their try me page is at the following.

    https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_trigger_button_enter

    This worked in my regular browser but did not work in my php app which uses the built in php browser.

    After toying a bit I came up with the following pure JavaScript alternative that works for my situation and should work in every other situation:

        function checkForEnterKey(){
            if (event.keyCode === 13) {
                event.preventDefault();
                document.getElementById("myBtn").click();
            }
        }
    
        function buttonClickEvent()
        {
            alert('The button has been clicked!');
        }
    

    HTML Press the enter key inside the textbox to activate the button.

        <br />
        <input id="myInput" onkeyup="checkForEnterKey(this.value)">
        <br />
        <button id="myBtn" onclick="buttonClickEvent()">Button</button>
    
    0 讨论(0)
  • 2020-12-04 08:49
    <input type="text" id="input_id" />    
    
    $('#input_id').keydown(function (event) {
        if (event.keyCode == 13) { 
             // Call your function here or add code here
        }
    });
    
    0 讨论(0)
  • 2020-12-04 08:51

    There are a js-free solution.

    Set type=submit to the button you'd like to be default and type=button to other buttons. Now in the form below you can hit Enter in any input fields, and the Render button will work (despite the fact it is the second button in the form).

    Example:

        <button id='close_renderer_button' class='btn btn-success'
                title='Перейти к редактированию программы'
                type=button>
          <span class='glyphicon glyphicon-edit'> </span> Edit program
        </button>
        <button id='render_button' class='btn btn-primary'
                title='Построить фрактал'
                type=submit
                formaction='javascript:alert("Bingo!");'>
          <span class='glyphicon glyphicon-send'> </span> Render
        </button>
    

    Tested in FF24 and Chrome 35 (formaction is html5 feature, but type is not).

    0 讨论(0)
  • 2020-12-04 08:55

    Based on some previous answers, I came up with this:

    <form>
      <button id='but' type='submit'>do not click me</button>
      <input type='text' placeholder='press enter'>
    </form>
    
    $('#but').click(function(e) {
      alert('button press');
      e.preventDefault();
    });
    

    Take a look at the Fiddle

    EDIT: If you dont want to add additional html elements, you can do this with JS only:

        $("input").keyup(function(event) {
            if (event.keyCode === 13) {
                $("button").click();
            }
        });     
    
    0 讨论(0)
  • 2020-12-04 08:56

    It is…… 2020. And I believe this still holds true.


    DO NOT USE keypress

    1. keypress event is not triggered when the user presses a key that does not produce any character, such as Tab, Caps Lock, Delete, Backspace, Escape, left & right Shift, function keys(F1 - F12).

      keypress event Mozilla Developer Network

      The keypress event is fired when a key is pressed down, and that key normally produces a character value. Use input instead.

    2. It has been deprecated.

      keypress event UI Events (W3C working draft published on November 8, 2018.)

      • NOTE | The keypress event is traditionally associated with detecting a character value rather than a physical key, and might not be available on all keys in some configurations.
      • WARNING | The keypress event type is defined in this specification for reference and completeness, but this specification deprecates the use of this event type. When in editing contexts, authors can subscribe to the beforeinput event instead.

    DO NOT USE KeyboardEvent.keyCode

    1. It has been deprecated.

      KeyboardEvent.keyCode Mozilla Developer Network

      Deprecated | This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.


    What should I use then? (The good practice)

    // Make sure this code gets executed after the DOM is loaded.
    document.querySelector("#addLinks").addEventListener("keyup", event => {
        if(event.key !== "Enter") return; // Use `.key` instead.
        document.querySelector("#linkadd").click(); // Things you want to do.
        event.preventDefault(); // No need to `return false;`.
    });
    
    0 讨论(0)
  • 2020-12-04 09:01

    I am using a kendo button. This worked for me.

    <div class="form-group" id="indexform">
        <div class="col-md-8">
                <div class="row">
                    <b>Search By Customer Name/ Customer Number:</b>
                    @Html.TextBox("txtSearchString", null, new { style = "width:400px" , autofocus = "autofocus" })
                    @(Html.Kendo().Button()
                        .Name("btnSearch")
                        .HtmlAttributes(new { type = "button", @class = "k-primary" })
                        .Content("Search")
                        .Events(ev => ev.Click("onClick")))
                </div>
        </div>
    </div>
    <script>
    var validator = $("#indexform").kendoValidator().data("kendoValidator"),
              status = $(".status");
    $("#indexform").keyup(function (event) {
        if (event.keyCode == 13) {
            $("#btnSearch").click();
        }
    });
    </script>
    
    0 讨论(0)
提交回复
热议问题