user3498478 user3498478 - 5 months ago 25
jQuery Question

Jquery: how to trigger click event on pressing enter key or clicking button

I have a button that triggers a jquery event but only if the button is clicked. Is it possible to make it work if it is clicked or the return key is used?

$(document).ready(function () {
var zipCodes = [60538, 60504];
$("#buttontest").click(function () {
var zipIndex = zipCodes.indexOf(parseInt($("#full_day").val()));
$("#zipMessage > div").hide("fast");
var zipId = zipIndex > -1 ? zipCodes[zipIndex] : "Error";
$("#zip" + zipId).show("fast");
});
});


Here is a working example; http://jsfiddle.net/7SPGh

Answer

As long as the button has focus, enter will trigger the click event. I think you mean you'd like to trigger a click if enter is pressed while the textbox has focus...

So, add a keydown handler to the textbox (fiddle):

$("#full_day").keydown(function(e){
    if(e.which === 13){
        $("#buttontest").click();
    }
});