How can I type only numeric characters in TextBox?

A

anonieko

This applies to javascript dynamic textbox onkeyNewsgroups: comp.lang.javascript
From: Lasse Reichstein Nielsen <[email protected]> - 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;
}
 
C

Com

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/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top