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

JavascriptHtmlbutton

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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>

Solution 2 - Javascript

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

Solution 3 - Javascript

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>

Solution 4 - Javascript

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.

Solution 5 - Javascript

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

Solution 6 - Javascript

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.

Solution 7 - Javascript

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.

Solution 8 - Javascript

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

Solution 9 - Javascript

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

Solution 10 - Javascript

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>

Solution 11 - Javascript

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.

Solution 12 - Javascript

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.

Solution 13 - Javascript

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

Solution 14 - Javascript

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.

Solution 15 - Javascript

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>

Solution 16 - Javascript

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

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

Solution 17 - Javascript

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

Solution 18 - Javascript

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

Solution 19 - Javascript

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

Solution 20 - Javascript

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.

Solution 21 - Javascript

For jQuery mobile, I had to do:

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

Solution 22 - Javascript

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

Solution 23 - Javascript

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.

Solution 24 - Javascript

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.

Solution 25 - Javascript

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

Solution 26 - Javascript

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>

Solution 27 - Javascript

These day the change event is the way!

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

Solution 28 - Javascript

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

Solution 29 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkdenneyView Question on Stackoverflow
Solution 1 - JavascriptSteve PauloView Answer on Stackoverflow
Solution 2 - JavascriptSergey IlinskyView Answer on Stackoverflow
Solution 3 - JavascriptkdenneyView Answer on Stackoverflow
Solution 4 - JavascriptalberteinView Answer on Stackoverflow
Solution 5 - JavascripticedwaterView Answer on Stackoverflow
Solution 6 - JavascriptVarunView Answer on Stackoverflow
Solution 7 - JavascriptSwittersView Answer on Stackoverflow
Solution 8 - JavascriptGiboltView Answer on Stackoverflow
Solution 9 - Javascriptme_anView Answer on Stackoverflow
Solution 10 - Javascriptmahbub_siddiqueView Answer on Stackoverflow
Solution 11 - JavascriptMax SchmelingView Answer on Stackoverflow
Solution 12 - JavascriptgarrowView Answer on Stackoverflow
Solution 13 - JavascriptfrhdView Answer on Stackoverflow
Solution 14 - JavascriptAlikElzin-kilakaView Answer on Stackoverflow
Solution 15 - JavascriptNVRMView Answer on Stackoverflow
Solution 16 - JavascriptMCCCSView Answer on Stackoverflow
Solution 17 - JavascriptStephen NgetheView Answer on Stackoverflow
Solution 18 - JavascriptLuke NezdaView Answer on Stackoverflow
Solution 19 - JavascriptKamil KiełczewskiView Answer on Stackoverflow
Solution 20 - JavascriptELEKView Answer on Stackoverflow
Solution 21 - Javascriptuser1071182View Answer on Stackoverflow
Solution 22 - JavascriptruffinView Answer on Stackoverflow
Solution 23 - JavascriptAlexandr TsyganokView Answer on Stackoverflow
Solution 24 - JavascriptEric EngelView Answer on Stackoverflow
Solution 25 - JavascriptclickbaitView Answer on Stackoverflow
Solution 26 - JavascriptUnmitigatedView Answer on Stackoverflow
Solution 27 - JavascriptDaniel De LeónView Answer on Stackoverflow
Solution 28 - JavascriptRavi MakwanaView Answer on Stackoverflow
Solution 29 - JavascriptNiraj ChauhanView Answer on Stackoverflow