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

This question is related to javascript htmlbutton

The answer is


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.


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

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


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.


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.


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.


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

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>

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

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

_x000D_
_x000D_
let client = navigator.userAgent.toLowerCase(),_x000D_
    isLinux = client.indexOf("linux") > -1,_x000D_
    isWin = client.indexOf("windows") > -1,_x000D_
    isMac = client.indexOf("apple") > -1,_x000D_
    isFirefox = client.indexOf("firefox") > -1,_x000D_
    isWebkit = client.indexOf("webkit") > -1,_x000D_
    isOpera = client.indexOf("opera") > -1,_x000D_
    input = document.getElementById('guestInput');_x000D_
_x000D_
if(isFirefox) {_x000D_
   input.setAttribute("placeholder", "ALT+SHIFT+Z");_x000D_
} else if (isWin) {_x000D_
   input.setAttribute("placeholder", "ALT+Z");_x000D_
} else if (isMac) {_x000D_
  input.setAttribute("placeholder", "CTRL+ALT+Z");_x000D_
} else if (isOpera) {_x000D_
  input.setAttribute("placeholder", "SHIFT+ESCAPE->Z");_x000D_
} else {'Point me to operate...'}
_x000D_
<input type="text" id="guestInput" accesskey="z" placeholder="Acces shortcut:"></input>
_x000D_
_x000D_
_x000D_


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.


For jQuery mobile, I had to do:

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

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


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.


For modern JS keyCode is deprecated, use key instead

searchInput.onkeyup = function (e) {
    if (e.key === 'Enter') {
        searchBtn.click();
    }
}

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


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.


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

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


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

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


These day the change event is the way!

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

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

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

Short working pure JS

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

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

function doSomething() {
  console.log('');
}
_x000D_
<input type="text" id="txtSearch" />
<input type="button" id="btnSearch" value="Search" onclick="doSomething();" />
_x000D_
_x000D_
_x000D_


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


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

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

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.


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>