Skip to content Skip to sidebar Skip to footer

Bind Enter Key To Specific Button On Page

How can I bind the enter key on the persons keyboard to this specific button on the

Solution 1:

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

Solution 2:

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

Solution 3:

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

Solution 4:

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.


Solution 5:

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


Post a Comment for "Bind Enter Key To Specific Button On Page"