Page 1 of 1

abort user from typing certain chararcters

Posted: Wed Feb 28, 2007 3:43 am
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 !!

Posted: Wed Feb 28, 2007 4:02 am
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.