123

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();
    }
});
Liam
  • 25,247
  • 27
  • 110
  • 174
Ben
  • 2,178
  • 4
  • 17
  • 16

14 Answers14

124
$(document).ready(function(){
    $('#TextBoxId').keypress(function(e){
      if(e.keyCode==13)
      $('#linkadd').click();
    });
});
Man Programmer
  • 5,150
  • 2
  • 17
  • 18
  • 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 03 '15 at 19:45
  • [dmitry_romanov's answer](http://stackoverflow.com/a/24245592/8384) is better because it is pure html. – McKay Jun 26 '15 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 02 '15 at 18:39
  • It is not currently in a form, but the OP doesn't state that it can't be in a form? – McKay Aug 03 '15 at 15:14
  • Just to add this works great but the brackets around the action in the if statement seem to be missing. – tatty27 May 09 '16 at 10:53
  • @deebs if you add return false after it will stop your key presses from appearing in the input, I.E you can't type. – Tim at MastersAllen May 13 '16 at 13:07
  • @TimatMastersAllen I believe the 'return false' should be within the "if(e.keyCode==13)" block after the click event, meaning it only applies to enter press. That would still fire the click, then return false so that it's not submitting the form or some other action that 'enter' may cause – deebs May 13 '16 at 14:39
  • 2
    @deebs quite right, not sure what I did on the day but I must have been having a brain fart. – Tim at MastersAllen May 18 '16 at 08:26
  • 6
    **WARNING** [It is deprecated currently](https://stackoverflow.com/a/45650898/4510033). – Константин Ван Aug 22 '17 at 00:56
  • In this case, `==` produces unnecessary type-casting. Use `===` instead for optimization. – Константин Ван Aug 29 '17 at 08:35
  • I found I had to use deebs' suggestion above, adding a line for 'return false;' after the click event or my text was wiped from the input field. – kalinma Jul 31 '19 at 17:46
  • @deebs adding return false after click trigger will not let you type anything in textbox – Naveen Saroye Apr 11 '20 at 07:39
  • Can also use `e.preventDefault()` – tblev May 15 '20 at 20:53
96

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;`.
});
  • 2
    how about: `if (event.key == "Enter") { document.querySelector("#linkadd").click(); }` ? – Anupam Jul 29 '19 at 07:41
  • 2
    Note that `.key` isn't supported in all browsers: https://caniuse.com/#feat=keyboardevent-key – about 10% of people use browsers that don't support it. – Martin Tournoij Jul 31 '19 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 '20 at 03:55
  • @MartinTournoij Well, worry not about that. Those who don’t know what `.key` is are super minor (under 3%) now. – Константин Ван Nov 20 '20 at 04: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 :( – Enigma Plus Feb 16 '21 at 19:45
90

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

dmitry_romanov
  • 4,760
  • 1
  • 30
  • 35
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.

Quentin
  • 857,932
  • 118
  • 1,152
  • 1,264
7

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();
    }
}
Asad Saeeduddin
  • 45,116
  • 6
  • 87
  • 135
3

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

Sud
  • 31
  • 1
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();
    }
});
akash
  • 2,042
  • 3
  • 19
  • 32
Anshu
  • 7,697
  • 5
  • 29
  • 41
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();
    }
});
Milind Anantwar
  • 79,642
  • 23
  • 92
  • 120
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();
        }
    });     
Pablo Werlang
  • 374
  • 2
  • 10
1

Do not use Javascript for this solution!!!

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 that is associated with a submit type button or input has focus by the user, autofocus attribute is set on any form field, button, or input, or the user tab's into any of the form fields. Pressing ENTER or RETURN on the keyboard then automatically triggers the first available submit button or input control for that form.

So, instead of JavaScripting this, an easier solution is to just add tabindex=0 on any of your form fields or submit buttons inside a form element then autofocus on the first input control or submit button. Tabindex=0 assigns that input to the page's list of indexed tab order page items, and autofocus shifts focus to any of your form fields, triggering any submit button 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. 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 id="button2" name="button2" type="submit" value="submit" form="buttonform2" title="Submit" tabindex="0" role="button" aria-label="Submit">Submit</button>
</form>

Stop scripting everything! The browsers have had this native ability for almost 20 years!!

Stokely
  • 7,475
  • 1
  • 24
  • 15
  • What if we don't want the url to change i.e. this isn't a form submission – thepiercingarrow May 04 '22 at 21:19
  • 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 08 '22 at 22:32
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>
Scott Tovey
  • 132
  • 3
  • 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: https://stackoverflow.com/a/155265/3943968 – jordom Oct 03 '20 at 15:17
0

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.

qwr
  • 8,081
  • 5
  • 52
  • 86
-1
<input type="text" id="input_id" />    

$('#input_id').keydown(function (event) {
    if (event.keyCode == 13) { 
         // Call your function here or add code here
    }
});
Rishabh Jhalani
  • 949
  • 10
  • 20
-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>
corvair61
  • 1
  • 5