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
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:
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.