Use Javascript to detect enterkey press event and submit the form

Posted: September 1, 2008 in ASP.NET, Javascript
Tags: ,

This code is useful in almost all kind of forms that has a submit button. When any user press “Enter key” also called a Return key in a textbox, this code will detect if the Enter key is pressed or not and will perform the same action as directed in a code of Submit button. Type the following javascript code befor a “body” tag.

function DetectEnterPressed(e) {
var characterCode
if(e && e.which){ // NN4 specific code
e = e
characterCode = e.which
}
else {
e = event
characterCode = e.keyCode // IE specific code
}
if (characterCode == 13) return true // Enter key is 13
else return false
}

Type the following line of code in a code behind file. You can put this code in a page_load method and outside the IsPostBack event.

txtPassword.Attributes.Add("onkeypress","javascript:return DetectEnterPressed(event);");

Advertisements
Comments
  1. sandrar says:

    Hi! I was surfing and found your blog post… nice! I love your blog. 🙂 Cheers! Sandra. R.

  2. Andy says:

    what is e?

  3. ceramika says:

    the declaration of e is useless because you pass in the event object anyway.

  4. William Toh says:

    Line 8:
    e = event

    Should it the line below instead?

    e = e;

  5. ranjithagayathri says:

    good

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s