Prevent Enter Key using Asp.net Ajax

Today at work, I had a requirement where I had to prevent user from pressing enter key when they are on a particular textbox because it would cause the page to postback which I wanted to prevent. Using asp.net Ajax, you can register for the keypress event. The key press event gets an argument of type Sys.UI.DomEvent. The DomEvent object has a property called charCode which tells you which key the user has pressed.You can compare the charCode value with Sys.UI.Key.enter to check if the user has pressed enter key. On confirmation that user has pressed enter key, I make use of method exposed on DomEvent class called preventDefault. PreventDefault basically prevents the default action from happening which in my case prevents the enter key from being executed. Here is the code that prevents enter key from being executed by trapping keypress event on textbox.

image

Published Wednesday, May 28, 2008 9:48 PM by zhirani

Comments

# re: Prevent Enter Key using Asp.net Ajax

Thursday, May 29, 2008 1:03 AM by preishuber

Nice sample- but why you make removehandler?

if the page is away, also every handler is away - or i miss something?

# re: Prevent Enter Key using Asp.net Ajax

Thursday, May 29, 2008 4:00 AM by athina.bikaki

Well, it’s a good practice to always dispose event handlers added to DOM elements. You do so to prevent memory leaks in the browser that could slow the application and cause a huge performance drop.

# re: Prevent Enter Key using Asp.net Ajax

Wednesday, June 18, 2008 8:44 AM by xaeryan

Great job, just what I needed!

# re: Prevent Enter Key using Asp.net Ajax

Wednesday, April 1, 2009 2:21 PM by Tony W

Excellent example! Clean and simple.

I looked in more than a few places, and everyone wanted to use the .preventDefault() method on a window event (duh!), rather than for a specific control.

Thanks alot!

Tony