1

I have a button that has the onclick event. How can I trigger it with a particular keypress? I'm stumped. ~:(

in the html

<button id="upButt" onclick='library.cmd()'>Up Direction</button>

in the jQuery

$(function() {
var e = $.Event('keypress');
e.which = 68;  //UP key
$('#pre').trigger(e);
});

3 Answers 3

3

I have created JSfiddle link for the same:-

http://jsfiddle.net/c2S5d/26/

Code:-

$(function() {
    $(document).keydown(function(e) {
        switch (e.which) {
            case 38: // up key
                alert("up key event called")
                $("#upButt").trigger("click")
                break;
        }
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

You are my lord and savior @devendra-soni
0

here is the solution for enter keypress: http://jsfiddle.net/qmruwn0a/

<input type="text">
<button id="btn">Click</button>

$('input').keypress(function(e) {
    if(e.which == 13) { //for key up use 38 
        $('#btn').trigger('click');
    }
});

$('#btn').on('click', function() {
    alert("click");
});

change the e.which value to any key code you like.

Comments

0

If you want it to work with any key add this to the button

onkeypress="this.onclick()" 

1 Comment

However, keep in mind, this will also be called by the TAB key, so it's not ideal for accessibility.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.