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

So the code that I have so far is:

<fieldset id="LinkList">
    <input type="text" id="addLinks" name="addLinks" value="http://">
    <input type="button" id="linkadd" name="linkadd" value="add">
</fieldset>

It is not in a <form> and is just as it is within a <div>. However when I type something into the textbox called "addLinks" I want the user to be able to press Enter and trigger the "linkadd" button which will then run a JavaScript function.
How can I do this?
Thanks

Edit: I did find this code, but it doesnt seem to work.

$("#addLinks").keyup(function(event){
    if(event.keyCode == 13){
        $("#linkadd").click();
    }
});

This question is related to html jquery button input textbox

The answer is


You could add an event handler to your input like so:

document.getElementById('addLinks').onkeypress=function(e){
    if(e.keyCode==13){
        document.getElementById('linkadd').click();
    }
}

First of all add jquery library file jquery and call it in your html head.

and then Use jquery based code...

$("#id_of_textbox").keyup(function(event){
    if(event.keyCode == 13){
        $("#id_of_button").click();
    }
});

This should do it, I am using jQuery you can write plain javascript.
Replace sendMessage() with your functionality.

$('#addLinks').keypress(function(e) {
    if (e.which == 13) {
        sendMessage();
        e.preventDefault();
    }
});

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();
        }
    });     

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>

Do not use Javascript for this!

Modern HTML pages automatically allow a form's submit button to submit the page with the ENTER/RETURN key when any form field control in the web page has focus by the user, autofocus attribute is set on a form field or button, or user tab's into any of the form fields.

So instead of Javascripting this, an easier solution is to add tabindex=0 on your form fields and button inside a form element then autofocus on the first input control. The user can then press "ENTER" to submit the form at any point as they enter data:

<form id="buttonform2" name="buttonform2" action="#" method="get" role="form">
  <label for="username1">Username</label>
  <input type="text" id="username1" name="username" value="" size="20" maxlength="20" title="Username" tabindex="0" autofocus="autofocus" />
  <label for="password1">Password</label>
  <input type="password" id="password1" name="password" size="20" maxlength="20" value="" title="Password" tabindex="0" role="textbox" aria-label="Password" />
  <button id="button2" name="button2" type="submit" value="submit" form="buttonform2" title="Submit" tabindex="0" role="button" aria-label="Submit">Submit</button>
</form>

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).


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>

<input type="text" id="input_id" />    

$('#input_id').keydown(function (event) {
    if (event.keyCode == 13) { 
         // Call your function here or add code here
    }
});

It works when input type="button" is replaced with input type="submit" for the default button which needs to be triggered.


  1. Replace the button with a submit
  2. Be progressive, make sure you have a server side version
  3. Bind your JavaScript to the submit handler of the form, not the click handler of the button

Pressing enter in the field will trigger form submission, and the submit handler will fire.


It is, yeah, 2021. 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.

  1. 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;`.
});

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to button

How do I disable a Button in Flutter? Enable/disable buttons with Angular Disable Button in Angular 2 Wrapping a react-router Link in an html button CSS change button style after click Circle button css How to put a link on a button with bootstrap? What is the hamburger menu icon called and the three vertical dots icon called? React onClick function fires on render Run php function on button click

Examples related to input

Angular 4 - get input value React - clearing an input value after form submit Min and max value of input in angular4 application Disable Button in Angular 2 Angular2 - Input Field To Accept Only Numbers How to validate white spaces/empty spaces? [Angular 2] Can't bind to 'ngModel' since it isn't a known property of 'input' Mask for an Input to allow phone numbers? File upload from <input type="file"> Why does the html input with type "number" allow the letter 'e' to be entered in the field?

Examples related to textbox

Add two numbers and display result in textbox with Javascript How to check if a text field is empty or not in swift Setting cursor at the end of any text of a textbox Press enter in textbox to and execute button command javascript getting my textbox to display a variable How can I set focus on an element in an HTML form using JavaScript? jQuery textbox change event doesn't fire until textbox loses focus? PHP: get the value of TEXTBOX then pass it to a VARIABLE How to clear a textbox once a button is clicked in WPF? Get current cursor position in a textbox