36
<input type="button" id="save_post" class="button" value="Post" style="cursor:pointer;"/>

How can I bind the enter key on the persons keyboard to this specific button on the page? It's not in a form, and nor do I want it to be.

Thanks!

3
  • 1
    See also stackoverflow.com/questions/1402698/… Jul 20, 2016 at 22:15
  • 1
    Significant flaw with all methods presented to date: Textboxes will also submit on enter, instead of allowing for new lines.
    – Kaji
    Feb 13, 2018 at 4:28
  • @Kaji Shift+Enter should still work but I agree it's a problem
    – Artemis
    Jul 22, 2019 at 0:32

5 Answers 5

50

This will click the button regardless of where the "Enter" happens on the page:

$(document).keypress(function(e){
    if (e.which == 13){
        $("#save_post").click();
    }
});
21

If you want to use pure javascript :

document.onkeydown = function (e) {
  e = e || window.event;
  switch (e.which || e.keyCode) {
        case 13 : //Your Code Here (13 is ascii code for 'ENTER')
            break;
  }
}
3
  • Pure JavaScript option is always a bonus
    – kipper_t
    Mar 8, 2017 at 8:58
  • window.onkeydown or document.onkeydown? guess it doesn't matter in this case Feb 6, 2018 at 7:09
  • that's a global function, it won't be that smart to override it.
    – MennyMez
    Mar 10, 2019 at 13:01
13

using jQuery :

$('body').on('keypress', 'input', function(args) {
    if (args.keyCode == 13) {
        $("#save_post").click();
        return false;
    }
});

Or to bind specific inputs to different buttons you can use selectors

$('body').on('keypress', '#MyInputId', function(args) {
    if (args.keyCode == 13) {
        $('#MyButtonId').click();
        return false;
    }
});
2
  • Why do we need to return false? The form will not submit.
    – Mai
    Mar 3, 2015 at 4:00
  • 2
    Hi @Mai, in the question it specifically asks "It's not in a form, and nor do I want it to be"!
    – Parham
    Mar 6, 2015 at 21:18
3

Vanilla JS version with listener:

window.addEventListener('keyup', function(event) {
  if (event.keyCode === 13) {
    alert('enter was pressed!');
  }
});

Also don't forget to remove event listener, if this code is shared between the pages.

1
0

Maybe not quite what you're looking for but there is a HTML property that lets you assign a specific button called an access key to focus or trigger an element. It's like this:

<a href='https://www.google.com' accesskey='h'>

This can be done with most elements.

Here's the catch: it doesn't always work. for IE and chrome, you need to be holding alt as well. On firefox, you need to be holding alt and shift (and control if on mac). For safari, you need to be holding control and alt. On opera 15+ you need alt, before 12.1 you need shift and esc.

Source: W3Schools

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.