0

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();">
PoornaChandra
  • 341
  • 2
  • 9
  • 1
    Your `onkeypress` event is trying to call the method `val`, while your JS defines the function `validate`. These two things have to match. – ajp15243 Jan 09 '14 at 05:44
  • possible duplicate: http://stackoverflow.com/questions/19508183/how-to-force-input-to-only-allow-alpha-letters – Rahul Desai Jan 09 '14 at 05:45

3 Answers3

4
onkeypress="val()";

whereas you have written a method called validate()

so change it to

onkeypress="validate()";

Remaining seems good, see fiddle

Praveen
  • 55,303
  • 33
  • 133
  • 164
3

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;
}
Voonic
  • 4,667
  • 3
  • 27
  • 58
0

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

Edgar Villegas Alvarado
  • 18,204
  • 2
  • 42
  • 61