开发者

Bind enter key to specific button on page

<input type="button" id="save_post" class="button" value="Post" style="cu开发者_Go百科rsor: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!


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


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


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


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜