133

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();
    }
});
4
  • 3
    bind to keypress and check for e.charCode==13 (enter button). Oct 18, 2012 at 12:56
  • Have you added jquery library reference before using above code? Oct 18, 2012 at 13:02
  • Yes I did have the library referenced, not sure why it wasnt working, but its fine now. Thanks
    – Ben
    Oct 18, 2012 at 13:25
  • Yes, as @BradChristie mentioned, keypress or keydown mentioned in this answer are the way to go.
    – metakermit
    Jul 9, 2015 at 14:37

16 Answers 16

129
$(document).ready(function(){
    $('#TextBoxId').keypress(function(e){
      if(e.keyCode==13)
      $('#linkadd').click();
    });
});
13
  • 6
    adding 'return false' after the click event is helpful too, to avoid a default enter press on other buttons on the page
    – deebs
    Mar 3, 2015 at 19:45
  • dmitry_romanov's answer is better because it is pure html.
    – McKay
    Jun 26, 2015 at 12:40
  • 7
    @McKay, no it is not. Buttons can be used for things besides forms. In fact, the OP's question is explicitly not in a form.
    – Dan
    Aug 2, 2015 at 18:39
  • 2
    @deebs quite right, not sure what I did on the day but I must have been having a brain fart. May 18, 2016 at 8:26
  • 6
    WARNING It is deprecated currently. Aug 22, 2017 at 0:56
109

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;`.
});
5
  • 2
    how about: if (event.key == "Enter") { document.querySelector("#linkadd").click(); } ?
    – Anupam
    Jul 29, 2019 at 7:41
  • 2
    Note that .key isn't supported in all browsers: caniuse.com/#feat=keyboardevent-key – about 10% of people use browsers that don't support it. Jul 31, 2019 at 15:27
  • @Anupam Good, if you feel you don’t have to prevent the default event handler of the web browser, which, in this case (keyup), likely doesn’t exist. Nov 20, 2020 at 3:55
  • @MartinTournoij Well, worry not about that. Those who don’t know what .key is are super minor (under 3%) now. Nov 20, 2020 at 4:02
  • 2
    So there still isn't a nice way to do this with HTML. Back in VB6 days there were two properties on buttons: "Cancel" and "Default" If the button had Cancel=True, then hitting escape fired the button. If "Default" was true, enter or return triggered the button. I suppose I could JS that up using a class or two. Hope W3C read this :( Feb 16, 2021 at 19:45
100

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

10
  • 30
    only works if you are within a form, the OP isn't using a form
    – Andrew
    Jul 16, 2015 at 15:27
  • 1
    @Andrew Yes, I missed that. Now I can see it clearly, thank you. Jul 16, 2015 at 15:38
  • 7
    @Andrew, true, but it is trivial in most cases to wrap it in an do-nothing form... Aug 2, 2016 at 13:06
  • 3
    Additionally this solution works on iOS virtual keyboard [Go] button whose default action is to submit.
    – Elemental
    Mar 22, 2017 at 13:53
  • 3
    If you wrap it in a form with no action, it will not work in Firefox since submitting triggers a page reload. I was able to solve that problem by using the solution from stackoverflow.com/a/13118834/12440938 (action="javascript:void(0);")
    – gabriel
    Apr 9, 2021 at 19:20
14
  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.

8

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

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

4

Just use tabindex and autofocus HTML Attributes

(Do not use Javascript for this solution!!)

Newer evergreen browsers and older browsers automatically submit the first form submit button they find in the web page when the ENTER/RETURN key is pressed by a user. NO JAVASCRIPT NEEDED! Browsers have worked this way for nearly 20 years but new web developers have not bothered to learn about it.

If you have multiple submit buttons in a web page and want to control which submit button is pressed, its easy to do without JavaScript. Just set the tabindex to draw focus to the first form field set of controls that contains a submit button! Pressing the ENTER/RETURN keys will **trigger submission of form data when any form field control in the web page that is associated with a submit type button for that form has focus by the user.

To help with this focus, use the autofocus attribute set on any form field input in the form. The submit button for that form holding the input will then trigger when the ENTER/RETURN key is pressed. Otherwise, as mentioned above, pressing ENTER or RETURN on the keyboard automatically triggers the first available submit button for the page.

How to Combine tabindex with autofocus

Instead of JavaScripting focus, an easier solution is to just add tabindex=0 on any of your form fields or submit buttons inside a form element first, then autofocus on the first input control or submit button in your form and page. tabindex controls the order of which form fields and buttons get focus first. It is built into all browsers, old and new.

Tabindex=0 assigns equal focus to every input and button in the page's list of indexed tab order page items. This makes sure a new tab order form field list is reordered and explicitly focused on first. autofocus shifts focus to your chosen form field. Because the focus is now on this tabindex grouping inside one of your forms, pressing enter triggers the first submit button in that grouping to respond to the ENTER/RETURN key command.

The user can now press "ENTER" on their keyboard to submit the form at any point they like. This also has the advantage that the first form field is focused on and ready for data by the user.

Additional: You can enter tabindex=-1 on any buttons in the page to disable them from being in a tab index set or having tab focus. This also prevents them from being selected.

Lastly, never have orphaned input controls without a form HTML wrapper, like you have shown. Its not just broken HTML, but semantically wrong. HTML was designed to hold multiple HtML form tags. Because you can have multiple forms in a web page, you use <form> tags to control which form button goes with which form, or the "form" attribute set to the parent form holding it, as well as control user focus. Because you are using JavaScript to capture all form submissions, it does not matter what type (attribute) of buttons you use, or how you handle the scripts. All that matters is which ones will have FOCUS FIRST in the list.

FYI: <button> HTML elements always default to "submit" types if you do not add a type. Submit type buttons submit to the server, but JavaScript can easily shut that process down and stop submission. So it does not matter, except for the fact only submission types reliably respond to the ENTER event. You can use type=button for the type, which is just a non-submitting button. But I would stick with type=submit or no type which is the same (default) to avoid having type=button ones fail in some browsers.

An example below:

<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 type="submit" id="button2" name="button2" type="submit" value="submit" form="buttonform2" title="Submit" tabindex="0" role="button" aria-label="Submit">Submit</button>
</form>

Stop using JavaScript for simple solutions HTML can solve. HTML attributes used in web browsers have had this native ability for over 20 years. New web developers should know this.

6
  • 1
    What if we don't want the url to change i.e. this isn't a form submission May 4, 2022 at 21:19
  • 1
    Im guessing you mean you do not want the form to add a query string to the url when the submit button is triggered on ENTER? Simply set the method attribute on the form element as this: method="post"
    – Stokely
    May 8, 2022 at 22:32
  • 1
    Nice! It's so good to see some 20-year-old browser behaviour that is still relevant today :-) Just for clarification, if you have a button within your form that you don't want to be triggered when ENTER/RETURN is pressed within a control, make it <button type='button' ... /> not just <button ... />. The submit button for the form should be <button type='submit' ... /> or <submit /> Apr 14, 2023 at 15:08
  • That solution is fine except for the fact you cant submit multiple forms inside your page. So you just disabled them. If you are just using JavaScript for every form button submission then use the tabindex solution I mentioned and turn ALL BUTTONS to type=button. But that does not discount the value in maximizing your website for wider support in 20+ years of browsers :)
    – Stokely
    Apr 15, 2023 at 4:33
  • 1
    @thepiercingarrow If you dont need to submit your form fields to the server, just capture the submit using JavaScript. Nothing is submitted by the form in HTML in that case. If you are submitting the form traditionally using HTML and dont want the URL to change when you post using submit, simply use the attribute action="" or action="#" in the form HTML element to post to the same page. HTML is only designed to submit input fields. JavaScript is designed to disable that process. Mangling your HTML by hiding buttons or forms wont help.
    – Stokely
    Apr 17, 2023 at 4:53
1

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

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

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

Using pure HTML form:

<form class="my-form" action="javascript:myFunction();">
    <button>Submit</button>
</form>

By default, browsers will interpret Enter as submitting a form. <button> by default is type "submit" and accesses whatever is located in the form's action attribute (overridden if button's formaction is present). In this case for simplicity I use a javascript function with the javascript: pseudo-protocol, but it could be javascript event listener or a GET/POST method as in normal forms.

0

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>
1
  • It didn't work as I tried, you need to pass event in the checkForEnterKey function and the function should have event parameter too as shown here: stackoverflow.com/a/155265/3943968
    – jordom
    Oct 3, 2020 at 15:17
0

This is the bare bones of what you need. A form id and change the button type attribute to submit. Add the method attribute to prevent a URL change or page reload.

<form id='form1' method='dialog'>
    <input form="form1" type="text" />
    <button form="form1" type="submit"> </button>
</form>
0

This doesn't use jquery, but it should click your button on release of the enter key when focus is on the input box.

function consoleLog() {
  // Clicking the button itself will work as well.
  console.log("enter key pressed")
}

document.getElementById("my_textbox").addEventListener(
  "keyup",
  (e) => {
    if (e.key === "Enter") {
      document.getElementById("my_button").click()
    }
  });
<input id="my_textbox" type="text">
<button id="my_button" onclick="consoleLog()">Submit</button>

If you want the enter key to perform an action from anywhere on the page you can try the following instead.

window.addEventListener(
  "keyup",
  (event) => {
    if (event.key === "Enter") {
      document.getElementById("my_button").click()
    }
  }
);

The following MDN link documents the KeyboardEvent.key function

https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key

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

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

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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.