473,322 Members | 1,431 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

How can I type only numeric characters in TextBox?

This applies to javascript dynamic textbox onkey


Newsgroups: comp.lang.javascript
From: Lasse Reichstein Nielsen <l...@hotpop.com> - Find messages by
this author
Date: Fri, 15 Jul 2005 18:39:24 +0200
Local: Fri,Jul 15 2005 12:39 pm
Subject: Re: Summer 2005 browsers' test set ?
How can I make a Textbox get only Number Inputs in NN4 and IE5
Jan 26th, 2002 03:00

Alexander Beedie, Mr.India

ok, here's a neat way of using javascript to dynamically alter user
input on the fly, making use of regular expressions and string
manipulation... i finished developing this for a project yesterday, so
consider it hot off the press - usual disclaimers apply ;)
----------------------------------------------------------------------
[note, this script is currently verified only in IE5. i will be working

on NN4 compatibility later next week... i don't think there are any
serious obstacles to this, probably just a bit of tweaking]
----------------------------------------------------------------------

this example uses positive OR negative floating point numbers. you can
adapt it easily to integers, only positive numbers, only negative
numbers, or only text. indeed, i am going to make a library of such
functions in the coming weeks as and when i need them...

add the function call to your textbox's onKeyUp and onChange events.
(the onChange event is needed because incorrect values could otherwise
be pasted in with the mouse - with onChange these values are caught
when the box loses focus). the function takes two arguments; the name
of the textbox, and its current contents:
<input type="text" name="test" onKeyUp="allowOnlyFloatingPointNumbers
(test, test.value)" onChange="allowOnlyFloatingPointNumbers(test,
test.value)">
now copy the functions below into your head script block. they are
pretty heavily commented, so feel free to adapt them as you see fit.

that's it. the textbox will now only allow correctly formatted floating

point numbers to be typed, and will filter out incorrect values on the
fly. try it!
// --------------------------------------------------------------------
// accept an inputbox and its value as arguments: remove non-digit
// characters from the value, then strip repeated '.' or '-' chars. if
// there is still a problem, generate an alert to inform the user. this
// should not be possible, but it's best not to underestimate anyone's
// ability to make things crash and burn...! ;)
// --------------------------------------------------------------------
function allowOnlyFloatingPointNumbers(textbox, val){
val = val.replace(/[^0-9.-]/g, ''); // strip non-digit chars
val = stripDuplicateChars(val, '.', 1, 0); // strip excess decimals
val = stripDuplicateChars(val, '-', 0, 1); // strip excess minus
signs
textbox.value = val; // replace textbox value
if (!isFloatingPointNumber(val)){ alert('This is not a valid number,
please correct it...');}
}

// --------------------------------------------------------------------
// checks string against regular expression for floating point number.
// --------------------------------------------------------------------
// note: we use '\d*' rather than the more correct '\d+', as we have
// to allow that the user is typing the input, not pasting it in ready
// formed. (ie: '-98.' is allowed with '\d*', but not '\d+', which
// would require '-98.0'). when i finish creating the library of
similar
// dynamic checks i'll add a call that strips trailing decimal points,
// or unique minus signs...
// --------------------------------------------------------------------
// returns boolean result
//
---------------------------------------------------------------------
function isFloatingPointNumber(val){
var fpnum = /^-{0,1}\d*\.{0,1}\d*$/g;
if (fpnum.test(val)){return true;} else {return false;}
}

// --------------------------------------------------------------------
// accepts two strings (str) and (strip), and two integers (n) and (s)
// as arguments: the 'strip' character specified is allowed to
// occur 'n' times in the 'str' string, counting from the starting
// index 's'.
// ie: stripDuplicateChars("xxxYYYxxxYYY", "x", 2, 0) --> "xxYYYYYY"
// stripDuplicateChars("xxxYYYxxxYYY", "Y", 1, 4) --> "xxxYYxxx"
// --------------------------------------------------------------------
// returns the modified string
// --------------------------------------------------------------------
function stripDuplicateChars(str, strip, n, s){
var count=0; var stripped=str.substring(0, s); var chr;
for (var i=s; i<str.length; i++){ chr = str.substring(i, i+1);
if (chr == strip){ count++; if (count<n+1){ stripped = stripped +
chr;}}
else {stripped = stripped + chr;}} return stripped;
}

Jul 23 '05 #1
2 13665
Com
<an******@hotmail.com> wrote
This applies to javascript dynamic textbox onkey

How can I make a Textbox get only Number Inputs


Return false from the onkeypress event if the key that triggered it does not
match \d, like so:

<input type="text" onkeypress="var k = event.keyCode ? event.keyCode :
event.charCode ? event.charCode : event.which; return /^(\d)$/.test(
String.fromCharCode(k) );">

Typing any non-numeric character will not have any effect while in this
textbox, the cursor will stay where it is. Note that arbitrary characters
can still be entered by pasting, dragging, etc. so when submitting the form,
the value still needs validation.

hth
ivo
http://4umi.com/web/javascript/
Jul 23 '05 #2

Nevermind what someone else wrote, do you have a Q?

Danny

On Fri, 15 Jul 2005 10:40:46 -0700, <an******@hotmail.com> wrote:
--
Using Opera's revolutionary e-mail client: http://www.opera.com/mail/
Jul 23 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Sanka | last post by:
I want to restrict users entering non numeric characters in a text box How can I do this? If there is any code sample please answer or email I'll be very glad Thank you
9
by: Bernie Yaeger | last post by:
I'm trying to control the textbox keypress event to deal with a "." such that it disallows a second "." and no characters after 2 numbers beyond the "." (thus a currency value). I have no problem...
16
by: Keith | last post by:
Am I crazy - to be shocked that there is no Numeric, Alpha, and AlphaNumeric Property in on the Textbox control I searched and searched - and found other people's code - but they don't work...
11
by: Keith | last post by:
I apologize for those of you who think I'm posting on the same topic. It is not that I don't appreciate all of your comments - and I'm definitely reading them all - but I think I have a differing...
0
by: Aaron Smith | last post by:
Is there an easy way to do a numeric mask on a DataGridTextBoxColumn? I need to only allow entry of numeric value and have only one decimal. I already have a subclasses TextBox column that limits...
5
by: ScareCrow | last post by:
How do I go about limiting a textbox to accepting numeric key input from the keyboard in vb.net? --------------= Posted using GrabIt =---------------- ------= Binary Usenet downloading...
6
by: Kesavan Muthuvel | last post by:
I need a code to check instantly the value in textbox. The code is to not allow users even to enter alpha characters in the textbox. Thank you Kesavan Muthuvel Chennai INDIA
4
by: Dennieku | last post by:
Hi, I have to develop an on-screen keyboard and on-screen numeric keypad for a touchscreen UI. The hardest thing with this is that it has to be multi-lingual. Has anybody have ideas how to...
5
lotus18
by: lotus18 | last post by:
Hello World! I have a sample code here written in vb .net that restricts the textbox to accept only alpha, alphanumeric or numeric characters. Public Enum MyOption Alpha = 1 ...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.