ChatGPT解决这个技术问题 Extra ChatGPT

Trigger a button click with JavaScript on the Enter key in a text box

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();" />
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.
@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.

B
Black

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."); }); Username:
Password: 

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."); } Username:
Password: 


It is probably a better practice to query event.which than event.keyCode or event.charCode, see developer.mozilla.org/en/DOM/event.charCode#Notes
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.
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.
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!
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.
i
icedwater

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();"
/>

Yeah I almost did that. I guess it's just a personal preference thing...I like the more modular approach. ;)
if you need to stop the form submission:onkeydown="if (event.keyCode == 13) {document.getElementById('btnSubmit').click();event.returnValue=false;event.cancel=true;}"
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.
I agree with Sam, this code with this inline JS-code is ugly as hell. You should always separate HTML and JavaScript codes.
@Sam Never get your wisdom from puppets. 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. ;^)
A
Anik Islam Abhi

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>

e = e || window.event; // shortest way to get event
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!
and if you return false inside the if, you can avoid the key from being processed further:
i
icedwater

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.


Dudes! Read his entire question. There's already another submit button on the page, so this wouldn't work for him.
Fun fact, I recently tried to do this in SharePoint. However SharePoint already has a form that wraps around all your content, and any <form> 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.)
A <button type="submit" onclick="return doSomething(this)">Value</button> works to. The clue lies within the return keyword
@skybondsor - OTOH, as mentioned by garrow, 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 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.
C
Community

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

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


I really don't understand why the JQeuery answer has more upvotes. I cry for the webdevelopement community.
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.
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();}
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.
S
Sk8erPeter

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.


document.layers? Are you still supporting Netscape?!!
No you do not need to support Netscape. blog.netscape.com/2007/12/28/…
netscape.com doesn't even exists anymore (it redirects to aol.com) and yet there are still people supporting nescape, amazing.
evt.which ? evt.which : evt.keyCode is equal to evt.which || evt.keyCode
@LeartS I'd bet that's because there are still people using Netscape.
S
Switters

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.


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.
This won't work, as there is already another submit button in the page.
@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.
@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."
This is a great answer since it allows custom actions yet avoids the need for a bunch of fancy override code.
C
Community

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


this is so much more readable than any of the other answers.
P
Peter Mortensen

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

m
mahbub_siddique

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>

P
Peter Mortensen
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.


g
garrow

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.


f
frhd

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


A
AlikElzin-kilaka

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.


Here's a question about further info on the keyup options: stackoverflow.com/q/32155887/435605
M
MCCCS

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

<input onkeypress="if(event.key == 'Enter') {console.log('Test')}">

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

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

This is a no javascript way to keyboard shortcuts stuffs.

https://i.stack.imgur.com/Yb7GA.png

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


Doesn't seem to answer the OP's question around the special case of key=ENTER
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.
S
Stephen Ngethe

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();" />

K
Kamil Kiełczewski

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


b
beldaz

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();" />

Should also mention that it triggers on unfocus.
P
Peter Mortensen
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.


C
Community

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 />";
            }
        });
    }
});

H
HoldOffHunger

For jQuery mobile, I had to do:

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

.live is deprecated in jQuery 1.7. Is it still considered OK in jQuery Mobile?
A
Alexandr Tsyganok

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.


E
Eric Engel
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.


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().
S
Stefan van den Akker

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

D
Daniel De León

These day the change event is the way!

document.getElementById("txtSearch").addEventListener('change',
    () => document.getElementById("btnSearch").click()
);

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 I think a lot of people wouldn't want this behaviour...
U
Unmitigated

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!"); } });


R
Ravi Makwana

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
-- or --
check out running example https://stackoverflow.com/a/58010042/6631280

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


R
RustyH

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

N
Niraj Chauhan

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.


The question was for triggering a button click with the enter key in a textbox. Your solution is for a "watermark" type of functionality.