简体   繁体   中英

should not accept digits in text field

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();">
onkeypress="val()";

whereas you have written a method called validate()

so change it to

onkeypress="validate()";

Remaining seems good, see fiddle

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;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM