Reputation: 351
I'm working with a text field that should NOT accept digits in it. So I have written a script with function named validate(). Even though it looks working, it is very bad. The user is able to see the data (i mean, the unwanted digits) entered. I want to check the user input before displaying it. If the user entered data is not a digit, then only it should be visible. Is there a function like getch() of C-language in javascript (or) suggest me a solution for this?
Here is my code:
<script>
function validate()
{
var s=t1.value;
var res="";
for(i=0;i<s.length;i++)
{
var ascii=s.charCodeAt(i);
if(ascii<48 || ascii>57)
res+=String.fromCharCode(ascii);
}
t1.value=res;
}
</script>
<input type="text" id="t1" onkeypress="val();">
Upvotes: 0
Views: 115
Reputation: 18344
Try with this:
<script>
function validate(input){
return (event.keyCode < 48 || event.keyCode > 57);
}
</script>
<input type="text" id="t1" onkeydown="return validate(this);">
Running here: http://jsfiddle.net/edgarinvillegas/XPvU2/1/
Hope this helps. Cheers
Upvotes: 0
Reputation: 4775
Call this function on key press from your html element | DEMO
Number wil not be accepted and will not be visible in text box
<input type="text" onkeypress="return checks(this,event)" />
JavaScript
function checks(dis,ev)
{
var e = ev || window.event;
var key = e.which||e.keyCode;
if(key>=48 && key<=57)
return false;
else
return true;
}
Upvotes: 3