1

I want the onclick event of a link <a href='#' onclick='function()'> to activate when the enter button is pressed. This is supposed to work, but I don't seem to get it working. Trigger a button click with JavaScript on the Enter key in a text box . And this also didn't work for a button.

The reason for this is probably because I run and load most of my interface in with ajax because of loading issues, certain calculations take quite some time, so I figured I should use ajax to show my page elements so I can update real time instead of making the user wait 5 to 10 seconds for the server. This however seems to make the code below not working.

My code

//This comes from a different php file which is read out on the server with
//readfile() in php after an ajax call. In other words it echoes the 
//contents of this file on the page including this link. 
echo "<a href='#' onclick='dosomething()' ID='Enter'>Click me</a>";

//js
$("#Enter").keyup(function(event){
    if(event.keyCode == 13){
        $("#Enter").click();
    }
});

function dosomething(){
    //activate some code depends on the link.
}

So how do I get this working. Activating the onclick on enter pressed on a link imported via ajax? Is this even possible?

Community
  • 1
  • 1
kpp
  • 800
  • 2
  • 11
  • 27

2 Answers2

2

Working Demo

Try this,

Use keypress event and it won't fire on #Enter as it is an <a> tag.

$(document).keypress(function(event){

    if(event.keyCode == 13){
        $("#Enter").click();   //OR $("#Enter").trigger('click');
    }
});

function dosomething(){
    alert('..');
    //activate some code depends on the link.
}
Shaunak D
  • 20,588
  • 10
  • 46
  • 79
0

You can do like

$("#Enter").keypress(function(event){
    if(event.keyCode == 13){
       dosomething();
    }
});

Even you can Trigger it like

$("#Enter").trigger('click');
GautamD31
  • 28,552
  • 10
  • 64
  • 85
  • well that would be great, however I would like this one function to run on all links in the application with the Enter ID, and no none of these links will ever be displayed at the same time. plus in some cases it requires user input. Like with Login(). So that would completely break it causing some random error message to pop up on your page because enter was pressed. – kpp Jun 17 '14 at 07:38
  • Then you have to use class selector instead of ID,because as per DOM rule you have to put the ID as unique – GautamD31 Jun 17 '14 at 07:39
  • can you show me how to, I am pretty familiar with php, but not so much with jquery – kpp Jun 17 '14 at 07:40