user1108948
user1108948

Reputation:

press 'Enter' key to invoke a function

In my page there is a button and a text box.

Originally I invoke a function by click the button. Now I also want to implement it by press Enter key as well. But it is not working. Press Enter key doesn't reach myFunction.

<script type="text/javascript">
     $(document).ready(function () {
         $("#txt1").keyup(function (event) {
         if (event.keyCode == 13) {
             $("#btn1").click(myFunction);
         }
     });
         $('#btn1').click(myFunction);

     });
     function myFunction() {
         // do something, press enter key doesn't reach here.
         })
     }
  </script>

Upvotes: 0

Views: 280

Answers (2)

PSL
PSL

Reputation: 123739

You are almost right: Just invoke the handler with .click() or .trigger('click')

 $(document).ready(function () {
    $("#txt1").keyup(function (event) {
    if (event.which== 13) {
        $("#btn1").click(); // Just do a click.
     }
   });

     $('#btn1').click(myFunction); //Your handler is already registered here.

});
function myFunction() {
         // do something, press enter key doesn't reach here.

}

Also use event.which instead of event.keyCode when inside jquery event handler as it normalizes event.keyCode and event.charCode.

Upvotes: 4

Ionică Bizău
Ionică Bizău

Reputation: 113365

Instead of

$("#btn1").click(myFunction);

I reccommend to use:

$("#btn1").on("click", function () {
   myFunction();
});

And then:

if (event.keyCode == 13) {
     $("#btn1").click(); //click the button
}

JSFIDDLE

Upvotes: 1

Related Questions