abort user from typing certain chararcters

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
PHPycho
Forum Contributor
Posts: 336
Joined: Fri Jan 06, 2006 12:37 pm

abort user from typing certain chararcters

Post by PHPycho »

Case:
Suppose i have a input text field which is supposed to take only numbers ie 0-9
If the user types any alphabets or any non numeric no then Javascript
should display the alert at the time and writing and then any written alphabets or any non numeric no should be deleted.
I mean to say is that suppose i am typing 123 and then try to write `q` then at that instant JS
should give alert and delete that written `q`.
Its very challenging for me...But Hope I will get my problem solved ...How ??
Obviously from this forum...hehehe............
Thanks in advance to all of you !!
User avatar
CoderGoblin
DevNet Resident
Posts: 1425
Joined: Tue Mar 16, 2004 10:03 am
Location: Aachen, Germany

Post by CoderGoblin »

Please do a little bit of homework first... Below is an example found using google in less than a minute...

Code: Select all

<script type="text/javascript">
function numbersonly(e){
var unicode=e.charCode? e.charCode : e.keyCode
if (unicode!=8){ //if the key isn't the backspace key (which we should allow)
if (unicode<48||unicode>57) //if not a number
return false //disable key press
}
}
</script>

<form>
<input type="text" size=18 onkeypress="return numbersonly(event)">
</form>
You should also allow for tab and return.

A couple of other points I would like to point out...
1) Don't use an alert (add a text next to the field, clear text if valid) as it doesn't require a user to move the mouse/click or press return.
2) You still need to validate the result in PHP whatever on the server side as javascript may be switched off.
Post Reply