Thursday, September 17, 2009

Avoid numbers in Textbox using ASP.NET AJAX

An old question which was recently asked for an interview.

How can you prevent numbers from being entered into a Textbox, using Microsoft ASP.NET AJAX Framework. Thinking about UpdatePanel’s? Be clever, I have some client-side codes, using the framework itself.

[Client-Side]

   1: <script type="text/javascript">
   2:     function pageLoad() {
   3:         var tbox = $get("Text1");
   4:         $addHandler(tbox, 'keypress', text1_keypress);
   5:     }
   6:  
   7:     function text1_keypress(e) {
   8:         var code = e.charCode;
   9:         if (code >= 48 && code <= 57)
  10:             e.preventDefault();
  11:     }
  12:  
  13:     function pageUnload() {
  14:         var tbox = $get("Text1");
  15:         $removeHandler(tbox, 'keypress', text1_keypress);
  16:     }
  17: </script>

[Markup-Code]

   1: <form id="form1" runat="server">
   2: <asp:ScriptManager ID="ScriptManager1" runat="server">
   3: </asp:ScriptManager>
   4: <div>
   5:     Enter text value:
   6:     <input id="Text1" type="text" />
   7: </div>
   8: </form>

Thanks.

No comments:

 
Best viewed in Internet Explorer 8.