Prevent Enter Key using 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 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.



  • Nice sample- but why you make removehandler?
    if the page is away, also every handler is away - or i miss something?

  • 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.

  • Great job, just what I needed!

  • 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!


Comments have been disabled for this content.