Jinesh
Jinesh

Reputation: 2575

How to generate a 'enter' event?

it is possible to generate a click event like this.

$("#elementId").trigger("click");

but I am confused how we can generate an 'enter' event similarly? I searched through internet and one way I found was,

$("#elementId").trigger("keypress",[13]);

but this is not working for me? Is this is correct? or is there any other way to do this?

Upvotes: 3

Views: 748

Answers (4)

Andreas Wong
Andreas Wong

Reputation: 60526

This?

var e = $.Event("keydown", { keyCode: 13 });
$("#elementId").trigger(e);

http://api.jquery.com/category/events/event-object/

Upvotes: 1

Prasenjit Kumar Nag
Prasenjit Kumar Nag

Reputation: 13461

You can use the following code to trigger a Enter keypress event

var e = jQuery.Event("keydown");
e.which = 13; // # Enter key code value
$("#elementId").trigger(e);

Upvotes: 1

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

Do you mean something like:

var e = jQuery.Event("keydown");
e.which = 13; // # Some key code value for Enter
$("input").trigger(e);

Upvotes: 1

Sagiv Ofek
Sagiv Ofek

Reputation: 25270

your syntax is incorrect. if you need the keycode try:

$("#elementId").keypress(function(e) {
  if ( e.which == 13 ) {
     //do stuff here
   }    
});

if you just want an event once the element is focus, try the focus() syntax.

$("#elementId").focus(function(){ ... });

Upvotes: 0

Related Questions