1449

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 inside the text box?

There is already a different submit button on my current page, so I can't simply make the button a submit button. And, I only want the Enter key to click this specific button if it is pressed from within this one text box, nothing else.

<input type="text" id="txtSearch" />
<input type="button" id="btnSearch" value="Search" onclick="doSomething();" />
TylerH
  • 20,799
  • 66
  • 75
  • 101
kdenney
  • 18,343
  • 4
  • 31
  • 27
  • 5
    Important note for rookies like me: The key part of this question is if you already have a form on the page so already have a submit button. The jQuery answer is cross browser compatible and a good solution. – Joshua Dance Aug 18 '14 at 17:38
  • 6
    @JoshuaDance, already having a form/submit is not a trouble. A page can have many forms (but not nested), each having their own submit. Every field of each form will trigger only the submit of that form. As stated by [this answer](http://stackoverflow.com/a/156905/1178314). – Frédéric Jan 14 '16 at 11:19

31 Answers31

1537

In jQuery, the following would work:

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

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

$("#myButton").click(function() {
  alert("Button code executed.");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Username:<input id="username" type="text"><br>
Password:&nbsp;<input id="pw" type="password"><br>
<button id="myButton">Submit</button>

Or in plain JavaScript, the following would work:

document.getElementById("id_of_textbox")
    .addEventListener("keyup", function(event) {
    event.preventDefault();
    if (event.keyCode === 13) {
        document.getElementById("id_of_button").click();
    }
});

document.getElementById("pw")
    .addEventListener("keyup", function(event) {
    event.preventDefault();
    if (event.keyCode === 13) {
        document.getElementById("myButton").click();
    }
});

function buttonCode()
{
  alert("Button code executed.");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Username:<input id="username" type="text"><br>
Password:&nbsp;<input id="pw" type="password"><br>
<button id="myButton" onclick="buttonCode()">Submit</button>
Black
  • 18,150
  • 39
  • 158
  • 271
Steve Paulo
  • 17,954
  • 2
  • 23
  • 23
  • 14
    It is probably a better practice to query event.which than event.keyCode or event.charCode, see https://developer.mozilla.org/en/DOM/event.charCode#Notes – William Niu Mar 25 '11 at 00:58
  • @William: As he's using `keyup`, and your link says *"`charCode` is never set in the `keydown` and `keyup` events. In these cases, `keyCode` is set instead."*, it doesn't matter. That said, though, I don't think `keyup` is the right event for the job (`keydown`, I would have thought; that's how a button behaves when it has focus, for instance). – T.J. Crowder Jun 02 '11 at 14:34
  • 28
    `keydown` not `keyup` is the better event to use. Also, if you are using asp.net you will have to `return false` at the end to stop asp.net from still intercepting the event. – maxp Jan 13 '12 at 10:49
  • 157
    Problem with using `keydown` is that holding down enter will fire the event over and over again. if you attach to the `keyup` event, it will only fire once the key is released. – Steve Paulo Apr 13 '12 at 17:29
  • 2
    `$(this).click();` looks nicer, and might will work with selectors that match more than one element (ie: `$('.buttons')`) – WhyNotHugo Jul 10 '12 at 18:28
  • I used $inputs = $('#foo,#bar'); $inputs.on('keydown', ...), and $inputs.off('keydown') when received an event to prevent auto-repeat, and return false to prevent wrong button being triggered. – Sam Watkins Jan 17 '13 at 07:04
  • 29
    I've tweaked your code adding `event.preventDefault();` before invoking `click();` function while my page has a form and I've switched `keyup` with `keypress` as it was the only working handler for me, anyways, thanks for neat piece of code! – Darj Feb 06 '13 at 01:02
  • This works for ff, chrome, ie in a asp.net app if you change it to keydown and add event.preventDefault() before the click() event. Hate that asp.net webforms app are so sensitive to this kind of crap. – PussInBoots Aug 11 '14 at 09:05
  • 3
    @Hugo You can't use `$(this)` because the parent ID is that of the textbox, and the one you want to `click()` on is the button ID. – unbindall Mar 15 '15 at 19:19
  • 2
    Why people hate jQuery so much? Any particular reason to discourage the use of jQuery? – sohaiby Oct 08 '15 at 09:47
  • 11
    To be fair, jQuery was pretty much synonymous with JS back when this answer was posted. But now a lot of us who avoid jQuery altogether (because it's just a waste of kb when you're using something like React) feel annoyed when we search for answers to JS questions and often the first thing that comes up is a library we don't want to depend on. – Andy Oct 09 '15 at 01:00
  • 4
    @sohaiby: if OP was using jquery, he would ask about it. And if he was not using jquery, suggesting it is overkill for such a simple task. It is the same as asking how to merge strings in C++ and receiving an answer about using Qt's QString. Technically valid, but not what the question was asking for. – George Y. Dec 21 '15 at 02:14
  • 2
    Please use `key` instead of `keyCode`. The latter is deprecated. – MCCCS Jan 29 '19 at 13:58
  • I voted up, but for some reason I had to use single quotes to make it work. Like this: document.getElementById('pw') and document.getElementById('id_of_button').click(); – Oleksiy Muzalyev Dec 06 '22 at 19:17
436

Then just code it in!

<input type = "text"
       id = "txtSearch" 
       onkeydown = "if (event.keyCode == 13)
                        document.getElementById('btnSearch').click()"    
/>

<input type = "button"
       id = "btnSearch"
       value = "Search"
       onclick = "doSomething();"
/>
icedwater
  • 4,701
  • 3
  • 35
  • 50
Sergey Ilinsky
  • 31,255
  • 9
  • 54
  • 56
  • 10
    if you need to stop the form submission:onkeydown="if (event.keyCode == 13) {document.getElementById('btnSubmit').click();event.returnValue=false;event.cancel=true;}" – Gabriel Chung Apr 09 '12 at 11:26
  • 1
    What about cross-browser compatibility? Does it work in all common browsers? (I see IE6 as common browser as it has still more than 5% of used browsers worldwide) – SimonSimCity Apr 17 '12 at 09:04
  • 4
    This worked for me due to fact that the inline method, instead of calling function with similar code in it, allows you to return false on the call and avoid postback. In my case the "click" method invokes a __doPostback async call and without the "return false;" would just reload the page. – Dave Apr 23 '12 at 15:35
  • 2
    @TimothyChung: Thanks immensely. The rest of this page is great, but I got here via Google trying to figure out how to keep an "Enter" on a text field from triggering a postback _without_ using a
    (which doesn't seem to work inside an asp:UpdatePanel). This works. (And it can be done inside a javascript function like kdenney's and probably in JQuery.)
    – RalphChapin Sep 18 '12 at 16:21
  • 4
    I agree with Sam, this code with this inline JS-code is ugly as hell. You should always separate HTML and JavaScript codes. – Sk8erPeter May 09 '13 at 10:06
  • 3
    Had to change `onkeydown` to `onkeypress` for it work in Chrome. – Seanny123 Sep 13 '13 at 10:49
  • 10
    @Sam Never get your [wisdom from puppets](https://www.youtube.com/watch?v=XQduN315etk&t=19m32s). Pain leads to *fear*, and fear is the mind-killer. Fear is the little-death that brings total obliteration. I will face my fear. I will permit it to pass over me and through me. And when it has gone past I will turn the inner eye to see its path. Where the fear has gone there will be nothing. Except maybe inline event handlers. So, yes, please separate your event handlers from your view/markup, as [this answer does](http://stackoverflow.com/a/20064004/1028230). ;^) – ruffin Dec 23 '15 at 17:51
186

Figured this out:

<input type="text" id="txtSearch" onkeypress="return searchKeyPress(event);" />
<input type="button" id="btnSearch" Value="Search" onclick="doSomething();" />

<script>
function searchKeyPress(e)
{
    // look for window.event in case event isn't passed in
    e = e || window.event;
    if (e.keyCode == 13)
    {
        document.getElementById('btnSearch').click();
        return false;
    }
    return true;
}
</script>
Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80
kdenney
  • 18,343
  • 4
  • 31
  • 27
  • 23
    e = e || window.event; // shortest way to get event – Victor Sep 20 '12 at 13:50
  • 3
    Best plain JavaScript option. Added JavaScript as an attribute in HTML is space-consuming, and jQuery is just jQuery (compatibility isn't guaranteed). Thanks for the solution! – unbindall Mar 15 '15 at 02:35
  • and if you return false inside the if, you can avoid the key from being processed further: – Jose Gómez Jul 13 '15 at 21:19
90

Make the button a submit element, so it'll be automatic.

<input type = "submit"
       id = "btnSearch"
       value = "Search"
       onclick = "return doSomething();"
/>

Note that you'll need a <form> element containing the input fields to make this work (thanks Sergey Ilinsky).

It's not a good practice to redefine standard behaviour, the Enter key should always call the submit button on a form.

icedwater
  • 4,701
  • 3
  • 35
  • 50
albertein
  • 26,396
  • 5
  • 54
  • 57
  • 35
    Dudes! Read his entire question. There's already another submit button on the page, so this wouldn't work for him. – skybondsor Jun 11 '14 at 16:56
  • 7
    Fun fact, I recently tried to do this in SharePoint. However SharePoint already has a form that wraps around all your content, and any `
    ` tags are thrown out by the otherwise liberal HTML parser. So I do have to hijack keypresses or bust. (BTW, pressing Enter in SharePoint launches Edit mode for some reason. I guess the ribbon is using the same form.)
    –  Mar 02 '15 at 21:21
  • 2
    A `` works to. The clue lies within the `return` keyword – Gus Apr 24 '17 at 22:59
  • @skybondsor - OTOH, [as mentioned by garrow](https://stackoverflow.com/a/156905/199364), OP was *incorrect* when he stated that limitation. It is entirely possible to have multiple forms on one page: just need to wrap the element inside its own form, and make sure that is *not inside* the other form on the page. – ToolmakerSteve Aug 28 '20 at 17:42
  • 2
    @ToolmakerSteve Of course! But we can both agree it was unclear from the original question whether multiple forms was a possibility. Another good reason to post as much of one's code as possible. – skybondsor Aug 29 '20 at 18:25
82

Since no one has used addEventListener yet, here is my version. Given the elements:

<input type = "text" id = "txt" />
<input type = "button" id = "go" />

I would use the following:

var go = document.getElementById("go");
var txt = document.getElementById("txt");

txt.addEventListener("keypress", function(event) {
    event.preventDefault();
    if (event.keyCode == 13)
        go.click();
});

This allows you to change the event type and action separately while keeping the HTML clean.

Note that it's probably worthwhile to make sure this is outside of a <form> because when I enclosed these elements in them pressing Enter submitted the form and reloaded the page. Took me a few blinks to discover.

Addendum: Thanks to a comment by @ruffin, I've added the missing event handler and a preventDefault to allow this code to (presumably) work inside a form as well. (I will get around to testing this, at which point I will remove the bracketed content.)

Community
  • 1
  • 1
icedwater
  • 4,701
  • 3
  • 35
  • 50
  • 17
    I really don't understand why the JQeuery answer has more upvotes. I cry for the webdevelopement community. – David Dec 21 '14 at 22:25
  • 2
    All you're really missing is an argument in your keypress handler and a `e.preventDefault()` to get it working with forms. See [my (new) answer](http://stackoverflow.com/a/34441952/1028230). – ruffin Dec 23 '15 at 18:52
  • 7
    unless you don't intend your users to actually enter any data, you should really do something like `if (event.keyCode == 13) { event.preventDefault(); go.click();} ` – unsynchronized Jun 22 '16 at 12:47
  • 2
    Using jQuery just for this tiny thing is sure useless. It also works much easily with CSP and takes less time to load. If you can, use this. – Avamander Apr 17 '17 at 12:23
62

In plain JavaScript,

if (document.layers) {
  document.captureEvents(Event.KEYDOWN);
}

document.onkeydown = function (evt) {
  var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : event.keyCode;
  if (keyCode == 13) {
    // For Enter.
    // Your function here.
  }
  if (keyCode == 27) {
    // For Escape.
    // Your function here.
  } else {
    return true;
  }
};

I noticed that the reply is given in jQuery only, so I thought of giving something in plain JavaScript as well.

Sk8erPeter
  • 6,899
  • 9
  • 48
  • 67
Varun
  • 5,001
  • 12
  • 54
  • 85
  • 22
    document.layers? Are you still supporting Netscape?!! – Victor Sep 20 '12 at 13:52
  • 7
    No you do not need to support Netscape. http://blog.netscape.com/2007/12/28/end-of-support-for-netscape-web-browsers/ – kingdango Jun 25 '13 at 20:02
  • 9
    netscape.com doesn't even exists anymore (it redirects to aol.com) and yet there are still people supporting nescape, amazing. – LeartS Apr 15 '14 at 19:04
  • 8
    `evt.which ? evt.which : evt.keyCode` is equal to `evt.which || evt.keyCode` – user May 17 '14 at 06:55
  • 4
    @LeartS I'd bet that's because there are still people _using_ Netscape. – SantiBailors Nov 30 '15 at 15:16
  • I don't understand why you check the availability of the `layers` feature in order to activate capturing of `Event.KEYDOWN`. What do those things have to do with each other? Test for `if (Event.KEYDOWN)` instead! – Mr Lister Jan 23 '20 at 12:07
  • @LeartS Well technically https://isp.netscape.com/ still exists (though it's basically the same as https://www.compuserve.com/). – user9811991 Jul 30 '21 at 03:15
30

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

Community
  • 1
  • 1
Gibolt
  • 42,564
  • 15
  • 187
  • 127
  • looks like `keypress` has been [deprecated](https://developer.mozilla.org/en-US/docs/Web/API/Element/keypress_event) – djvg May 25 '23 at 16:10
  • @djvg Is `keydown` more suitable now? – holydragon Jun 27 '23 at 03:28
  • 1
    @holydragon according to Mozilla's [`keypress` docs](https://developer.mozilla.org/en-US/docs/Web/API/Element/keypress_event): "Warning: Since this event has been deprecated, you should use `beforeinput` or `keydown` instead." – djvg Jun 27 '23 at 07:02
23

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.

Switters
  • 1,553
  • 2
  • 12
  • 13
  • This is a better solution for mobile device support. It automatically hides the keyboard on Android devices, and also iOS if you add `searchCriteria.blur();` to the `onsubmit`. – Aaron Gillion May 04 '15 at 22:52
  • This won't work, as there is already another submit button in the page. – Jose Gómez Jul 13 '15 at 21:29
  • @JoseGómez, a page can have as many submit buttons as the dev wishes, being triggered by their corresponding fields only. It only takes to have distinct forms for each group of fields/submit. A page is not limited to a single form. – Frédéric Jan 14 '16 at 11:15
  • @Frederic: from the question I (mis?)understood that the other submit button was in the same form: _"There is already a different submit button on my current page, so I can't simply make the button a submit button."_ – Jose Gómez Jan 14 '16 at 11:37
  • @JoseGómez, the question does not mandate to keep all in a single form. Many devs ignore they can put many forms in a single page. The way the OP has written its trouble's cause suggests he may be in that case. By example, lots of .Net webform devs believe html to be restricted to a single form per page, since .Net webform is restricted that way. But this is not a html restriction indeed. – Frédéric Jan 14 '16 at 15:18
  • 2
    This is a great answer since it allows custom actions yet avoids the need for a bunch of fancy override code. – Beejor Aug 19 '16 at 08:46
18

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();
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
me_an
  • 489
  • 4
  • 11
16

Try it:

<input type="text" id="txtSearch"/>
<input type="button" id="btnSearch" Value="Search"/>

<script>             
   window.onload = function() {
     document.getElementById('txtSearch').onkeypress = function searchKeyPress(event) {
        if (event.keyCode == 13) {
            document.getElementById('btnSearch').click();
        }
    };

    document.getElementById('btnSearch').onclick =doSomething;
}
</script>
mahbub_siddique
  • 1,755
  • 18
  • 22
15

Short working pure JS

txtSearch.onkeydown= e => (e.key=="Enter") ? btnSearch.click() : 1

txtSearch.onkeydown= e => (e.key=="Enter") ? btnSearch.click() : 1

function doSomething() {
  console.log('');
}
<input type="text" id="txtSearch" />
<input type="button" id="btnSearch" value="Search" onclick="doSomething();" />
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
14
onkeydown="javascript:if (event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('btnSearch').click();}};"

This is just something I have from a somewhat recent project... I found it on the net, and I have no idea if there's a better way or not in plain old JavaScript.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Max Schmeling
  • 12,363
  • 14
  • 66
  • 109
14

In modern, undeprecated (without keyCode or onkeydown) Javascript:

<input onkeypress="if(event.key == 'Enter') {console.log('Test')}">
MCCCS
  • 1,002
  • 3
  • 20
  • 44
  • This is in my opinion the simplest answer that does the job. In my use case, I upgraded it to onkeypress="inputKeyPressed(event)" and then handled the event.which parameter in the function itself. Enter key for example returns the event.which as 13. – ak93 Feb 01 '19 at 11:47
13

Although, I'm pretty sure that as long as there is only one field in the form and one submit button, hitting enter should submit the form, even if there is another form on the page.

You can then capture the form onsubmit with js and do whatever validation or callbacks you want.

garrow
  • 3,459
  • 1
  • 21
  • 24
13

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

frhd
  • 9,396
  • 5
  • 24
  • 41
12

In Angular2:

(keyup.enter)="doSomething()"

If you don't want some visual feedback in the button, it's a good design to not reference the button but rather directly invoke the controller.

Also, the id isn't needed - another NG2 way of separating between the view and the model.

AlikElzin-kilaka
  • 34,335
  • 35
  • 194
  • 277
10

This in-case you want also diable the enter button from Posting to server and execute the Js script.

<input type="text" id="txtSearch" onkeydown="if (event.keyCode == 13)
 {document.getElementById('btnSearch').click(); return false;}"/>
<input type="button" id="btnSearch" value="Search" onclick="doSomething();" />
Stephen Ngethe
  • 1,034
  • 13
  • 24
9

For jQuery mobile, I had to do:

$('#id_of_textbox').live("keyup", function(event) {
    if(event.keyCode == '13'){
    $('#id_of_button').click();
    }
});
HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
user1071182
  • 1,609
  • 3
  • 20
  • 28
9

This onchange attempt is close, but misbehaves with respect to browser back then forward (on Safari 4.0.5 and Firefox 3.6.3), so ultimately, I wouldn't recommend it.

<input type="text" id="txtSearch" onchange="doSomething();" />
<input type="button" id="btnSearch" value="Search" onclick="doSomething();" />
beldaz
  • 4,299
  • 3
  • 43
  • 63
9

Nobody noticed the html attibute "accesskey" which is available since a while.

This is a no javascript way to keyboard shortcuts stuffs.

accesskey_browsers

The accesskey attributes shortcuts on MDN

Intented to be used like this. The html attribute itself is enough, howewer we can change the placeholder or other indicator depending of the browser and os. The script is a untested scratch approach to give an idea. You may want to use a browser library detector like the tiny bowser

let client = navigator.userAgent.toLowerCase(),
    isLinux = client.indexOf("linux") > -1,
    isWin = client.indexOf("windows") > -1,
    isMac = client.indexOf("apple") > -1,
    isFirefox = client.indexOf("firefox") > -1,
    isWebkit = client.indexOf("webkit") > -1,
    isOpera = client.indexOf("opera") > -1,
    input = document.getElementById('guestInput');

if(isFirefox) {
   input.setAttribute("placeholder", "ALT+SHIFT+Z");
} else if (isWin) {
   input.setAttribute("placeholder", "ALT+Z");
} else if (isMac) {
  input.setAttribute("placeholder", "CTRL+ALT+Z");
} else if (isOpera) {
  input.setAttribute("placeholder", "SHIFT+ESCAPE->Z");
} else {'Point me to operate...'}
<input type="text" id="guestInput" accesskey="z" placeholder="Acces shortcut:"></input>
NVRM
  • 11,480
  • 1
  • 88
  • 87
  • 5
    Doesn't seem to answer the OP's question around the special case of key=ENTER – Ozan Bellik Oct 23 '17 at 21:47
  • 2
    This answer misunderstands *accesskey*, which is a way to have a key *focus* on an element - after pressing the access key for the text area, one could then start typing into it. OP is asking for something quite different: a way to submit the contents of the current element. – ToolmakerSteve Aug 28 '20 at 17:30
8
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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ELEK
  • 89
  • 1
  • 1
8

To add a completely plain JavaScript solution that addressed @icedwater's issue with form submission, here's a complete solution with form.

NOTE: This is for "modern browsers", including IE9+. The IE8 version isn't much more complicated, and can be learned here.


Fiddle: https://jsfiddle.net/rufwork/gm6h25th/1/

HTML

<body>
    <form>
        <input type="text" id="txt" />
        <input type="button" id="go" value="Click Me!" />
        <div id="outige"></div>
    </form>
</body>

JavaScript

// The document.addEventListener replicates $(document).ready() for
// modern browsers (including IE9+), and is slightly more robust than `onload`.
// More here: https://stackoverflow.com/a/21814964/1028230
document.addEventListener("DOMContentLoaded", function() {
    var go = document.getElementById("go"),
        txt = document.getElementById("txt"),
        outige = document.getElementById("outige");

    // Note that jQuery handles "empty" selections "for free".
    // Since we're plain JavaScripting it, we need to make sure this DOM exists first.
    if (txt && go)    {
        txt.addEventListener("keypress", function (e) {
            if (event.keyCode === 13)   {
                go.click();
                e.preventDefault(); // <<< Most important missing piece from icedwater
            }
        });

        go.addEventListener("click", function () {
            if (outige) {
                outige.innerHTML += "Clicked!<br />";
            }
        });
    }
});
Community
  • 1
  • 1
ruffin
  • 16,507
  • 9
  • 88
  • 138
7

For those who may like brevity and modern js approach.

input.addEventListener('keydown', (e) => {if (e.keyCode == 13) doSomething()});

where input is a variable containing your input element.

5
document.onkeypress = function (e) {
 e = e || window.event;
 var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
 if (charCode == 13) {

        // Do something here
        printResult();
    }
};

Heres my two cents. I am working on an app for Windows 8 and want the button to register a click event when I press the Enter button. I am doing this in JS. I tried a couple of suggestions, but had issues. This works just fine.

Eric Engel
  • 305
  • 4
  • 15
  • Sort of overkill to place the event handler on the document. If you had a `charCode` of 13 anywhere else, you're firing off the `printResult()`. – ruffin Dec 23 '15 at 18:44
4

To do it with jQuery:

$("#txtSearch").on("keyup", function (event) {
    if (event.keyCode==13) {
        $("#btnSearch").get(0).click();
    }
});

To do it with normal JavaScript:

document.getElementById("txtSearch").addEventListener("keyup", function (event) {
    if (event.keyCode==13) { 
        document.getElementById("#btnSearch").click();
    }
});
Stefan van den Akker
  • 6,661
  • 7
  • 48
  • 63
clickbait
  • 2,818
  • 1
  • 25
  • 61
3

In jQuery, you can use event.which==13. If you have a form, you could use $('#formid').submit() (with the correct event listeners added to the submission of said form).

$('#textfield').keyup(function(event){
   if(event.which==13){
       $('#submit').click();
   }
});
$('#submit').click(function(e){
   if($('#textfield').val().trim().length){
      alert("Submitted!");
   } else {
    alert("Field can not be empty!");
   }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="textfield">
Enter Text:</label>
<input id="textfield" type="text">
<button id="submit">
Submit
</button>
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
2

These day the change event is the way!

document.getElementById("txtSearch").addEventListener('change',
    () => document.getElementById("btnSearch").click()
);
Daniel De León
  • 13,196
  • 5
  • 87
  • 72
  • 4
    change events fire when the user commits a value change to a form control. This may be done, for example, by clicking outside of the control or by using the Tab key to switch to a different control. [MDN](https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onchange) I think a lot of people *wouldn't* want this behaviour... – Mattwmaster58 Jan 05 '21 at 02:43
1

My reusable Vanilla JS solution. so you can change which button gets hit depending on what element/textbox is active.

 <input type="text" id="message" onkeypress="enterKeyHandler(event,'sendmessage')" />
 <input type="button" id="sendmessage" value="Send"/>

function enterKeyHandler(e,button) {
    e = e || window.event;
    if (e.key == 'Enter') {
        document.getElementById(button).click();
    }
}
RustyH
  • 473
  • 7
  • 22
1

You can try below code in jQuery.

$("#txtSearch").keyup(function(e) {
    e.preventDefault();
    var keycode = (e.keyCode ? e.keyCode : e.which);
    if (keycode === 13 || e.key === 'Enter') 
    {
        $("#btnSearch").click();
    }
});
rsmdh
  • 128
  • 1
  • 2
  • 12
-2

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

// find elements
var banner = $("#banner-message")
var button = $("button")

// handle click and add class
button.on("click", function(){
    if(banner.hasClass("alt"))
    banner.removeClass("alt")
  else
    banner.addClass("alt")
})

$(document).ready(function(){
    $(document).on('keydown', function (e) {
        
         if (e.ctrlKey) {
            $('[class*="ctrl-"]:not([data-ctrl])').each(function (idx, item) {
                var Key = $(item).prop('class').substr($(item).prop('class').indexOf('ctrl-') + 5, 1).toUpperCase();
                $(item).attr("data-ctrl", Key);
                $(item).append('<div class="tooltip fade top in tooltip-ctrl alter-info" role="tooltip" style="margin-top: -61px; display: block; visibility: visible;"><div class="tooltip-arrow" style="left: 49.5935%;"></div><div class="tooltip-inner"> CTRL + ' + Key + '</div></div>')
            });
        }
         
        if (e.ctrlKey && e.which != 17) {
            var Key = String.fromCharCode(e.which).toLowerCase();
            if( $('.ctrl-'+Key).length == 1) {
                e.preventDefault();
                if (!$('#divLoader').is(":visible"))
                    $('.ctrl-'+Key).click();
                console.log("You pressed ctrl + "+Key );
            }
        }
    });
    $(document).on('keyup', function (e) {
        if(!e.ctrlKey ){
          $('[class*="ctrl-"]').removeAttr("data-ctrl");
            $(".tooltip-ctrl").remove();
        }
    })
});
#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="banner-message">
  <p>Hello World</p>
  <button class="ctrl-s" title="s">Change color</button><br/><br/>
  <span>Press CTRL+S to trigger click event of button</span>
</div>

-- or --
check out running example https://stackoverflow.com/a/58010042/6631280

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

Ravi Makwana
  • 2,782
  • 1
  • 29
  • 41
-4

This also might help, a small JavaScript function, which works fine:

<script type="text/javascript">
function blank(a) { if(a.value == a.defaultValue) a.value = ""; }

function unblank(a) { if(a.value == "") a.value = a.defaultValue; }
</script> 
<input type="text" value="email goes here" onfocus="blank(this)" onblur="unblank(this)" />

I know this question is solved, but I just found something, which can be helpful for others.

Niraj Chauhan
  • 7,677
  • 12
  • 46
  • 78
  • 6
    The question was for triggering a button click with the enter key in a textbox. Your solution is for a "watermark" type of functionality. – kdenney Sep 14 '11 at 13:23