Thursday, July 1, 2010

How to simulate Enter keypress event using JavaScript ?

Lets assume we have username and password textboxes and when the user presses the enter key on username / password then it should simulate submit keypress.



this.password.Attributes.Add("onkeypress", "return clickButton(event,'" + buttonLOGON.ClientID + "')");

this.username.Attributes.Add("onkeypress", "return clickButton(event,'" + buttonLOGON.ClientID + "')");


In the above example buttonLogon is the submit button.We pass the client-Id as parameter to the Javascript function.Lets look at the javascript function below which does the actual trick.


   1:  //Simulate Enter keypress.

   2:   function clickButton(e, buttonid)

   3:   { 

   4:        var evt = e ? e : window.event;

   5:        //Get the button for which the event has to be raised.

   6:        var bt = document.getElementById(buttonid);

   7:        if (bt){ 

   8:            //It enter key pressed ..

   9:            if (evt.keyCode == 13){ 

  10:                  //Raise button click event..

  11:                  bt.click(); 

  12:                  return false; 

  13:            } 

  14:        } 

  15:   }

No comments:

Post a Comment