ASP.NET VERSIONS: 1.0 | 1.1
Build a Textbox for Numeric Input
Editor's Note: This is a companion tip to "Hit Enter and Post Back," published in the February 2004 issue of asp.netPRO.
By Dino Esposito
var key = window.event.keyCode;
if (key <48 || key >57)
window.event.returnValue = false;
How can you filter out any keys that do not correspond to digits? The window.event object features the returnValue boolean property that denotes the return value for the event. Setting this property to false, you let the browser know that the last event (key pressed) was unsuccessful. As a result, the browser doesn't update its user interface and the key pressed is discarded.
The final touch regards the alignment of the digits. Normally, numbers are entered right-to-left, while the text flows left-to-right in input fields. Is there a way to influence the direction of the text in a control? On purpose, the HTML 4.0 standard defines the dir attribute. This attribute specifies the base direction of text in all HTML elements. Feasible values of the dir attribute are LTR (left-to-right, default) and RTL (right-to-left). Overall, a numeric textbox looks like the following:
These features can easily be integrated in a custom control. If you do so, make sure you test the browser's capabilities and override the Text property to ensure that non-numeric text is discarded if set programmatically. Required browser capabilities are HTML 4.0+ (dir attribute) and support for window.event (Internet Explorer 4.0 and higher).
Dino Esposito is a trainer and consultant who specializes in ASP.NET, ADO.NET, and XML. Author of Building Web Solutions with ASP.NET and ADO.NET and Programming Microsoft ASP.NET, both from Microsoft Press, Dino also is a co-founder of http://www.VB2TheMax.com. E-mail him at mailto:[email protected].