user3498478 user3498478 - 1 year ago 135
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;

Answer Source

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

    if(e.which === 13){
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download