Clicking a link when enter key is pressed using jQuery

后端 未结 7 1933
无人及你
无人及你 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:22

    I had a very similar question. However, I was unable to find a complete solution.

    I simply wanted to attach the same function to 2 different elements, with 2 different methods of executing it. For example, what Tom wanted: CLICK a link, OR press ENTER in an input field, and execute the same function (ie navigate to another page).

    Jacob Relkin has presented a good idea for the "enter" keypress. I have included this in the code below:

    So based on the following simple markup:

    Click me!

    Use this JavaScript (JQuery) code:

    //this is the plugin Jacob Relkin suggested
    (function($) {
    $.fn.enter=function(callback){
        this.keyup(function(e) {
            var ev = e || event;
            if(ev.keyCode == 13) {
                callback();
                return false;
            }
        }); 
    };
    })(jQuery);
    
    $(document).ready(function(){
    
        var fnDoStuff = function() {
            //insert code here
            //for this example I will complete Tom's task
            document.location.href = $("#myButton").attr('href');
        };
    
        $('#myInput').enter(fnDoStuff);
        $('#myButton').click(fnDoStuff);
    
     });
    

    In this way, you could attach the same function to any number of elements, with any type of interaction.

提交回复
热议问题