Clicking a link when enter key is pressed using jQuery

后端 未结 7 1930
无人及你
无人及你 2021-02-19 22:58

I\'m trying to make it so when a user is in a text box and they press enter, it is the same as clicking the link, in which case it should take them to another page. Here\'s what

7条回答
  •  情歌与酒
    2021-02-19 23:23

    You have a few major problems with this code...

    The first one, pygorex1 caught: you need to specify the event argument if you wish to refer to it...

    The second one is in the same area of your code: you're trying to check for the key event in a handler for the click event!

    The third one can be found on this line:

                //click the button and go to next page
                $("#button1").click();
    

    ...which does nothing, since you have no event handlers on that link, and jQuery's click() function does not trigger the browser's default behavior!

    Instead, try something like this:

    // if a key is pressed and then released
    $("#drivingSchoolInput").live("keyup", function(e) {
    
      // ...and it was the enter key...
      if(e.keyCode == 13) {
    
        // ...navigate to the associated URL.
        document.location = $("#button1").attr('href');
      }               
    });
    

提交回复
热议问题