Introduction
While writing the CodeProject article Multi-lingual Light Weight Report Writer with DrillDown, I needed to create a textbox which would only accept numbers.
I looked around the net and couldn't find what I wanted, so I wrote one.
Using the Code
Unzip the download into your project.
Include the following in the <head>
section of your *.aspx file.
<script src="JavascriptForceNumericInput.js"></script>
The function signature is:
ForceNumericInput(This, AllowDot, AllowMinus)
To allow positive and negative numbers with decimal point, code your input statement as:
<input type="text" name="YourFieldName" id="YourFieldName" value=""
onkeydown="ForceNumericInput(this, true, true)" />
To allow positive and negative integers, code your input statement as:
<input type="text" name="YourFieldName" id="YourFieldName"
value="" onkeydown="ForceNumericInput(this, false, true)" />
To allow only positive numbers with decimal point, code your input statement as:
<input type="text" name="YourFieldName" id="YourFieldName"
value="" onkeydown="ForceNumericInput(this, true, false)" />
To allow only positive integers, code your input statement as:
<input type="text" name="YourFieldName" id="YourFieldName"
value="" onkeydown="ForceNumericInput(this, false, false)" />
You must include an id
attribute or the code will not work. You do not need a name
attribute unless this is a form variable which will be submitted.
Points of Interest
This function was written using the Internet Explorer event model as the Light Weight Report Writer targeted ASPX applications and most of those are written for the Internet Explorer browser.
If anyone converts the code to a cross browser environment, please let me know and I'll repost the source and give credit to the author.
History
- 28th September, 2008: Initial version