Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click anchor tag link on enter press

I have an anchor tag like

<a class="btn btn-danger" id="clicking" data-bind="click: $root.enterLocation" href="#">Continue</a>

It's inside a pop-up. I need to click on this link on pressing enter key. I have tried the following code but it did not work for me.

$(document).ready(function(){ 
  $(document).keyup(function(event){
    if (event.keyCode == 13){
      $("#clicking").trigger('click');     
    }
  })
});

Not sure why the functionality is not working. I have used click function also with same result.Its working correctly on mouse click. I need to make it work automatically on enter press.

Following code is working fine in Firefox.

$(document).ready(function () {
  $(document).on("keyup", function (event) {
    if (event.which == 13) {
      document.getElementById("clicking").click();   
    }
  });
}); 

How to make this work on Chrome?

like image 706
Sanjib Karmakar Avatar asked Dec 10 '12 09:12

Sanjib Karmakar


1 Answers

I think the problem is that you're using event.keyCode, which isn't always used in all browsers. Some browsers use event.charCode or even a different event.which, which may be supported by what you're using. Anyways, the normal way to get the keycode from the event with jQuery is to use event.which.

jQuery normalizes the event object passed to the event handler and fixes "problems" like this so that you don't have to worry. At the same time, it seems that it copies over some of the original event's properties ("Most properties from the original event are copied over and normalized to the new event object." - from the jQuery API docs). That's probably why it's "working" for the other people commenting/answering. The event parameter passed to the handler has been generated/normalized by jQuery and will have everything you need, using the right properties. The correct way though, is to use event.which to get a normalized keycode for the event. http://api.jquery.com/event.which/

$(document).ready(function () {
    $(document).on("keyup", function (event) {
        if (event.which == 13) {
            $("#clicking").trigger('click');
        }
    });
});
like image 161
Ian Avatar answered Nov 08 '22 09:11

Ian