简体   繁体   English

不应在文本字段中接受数字

[英]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(). 因此,我编写了一个名为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? 是否有类似javascript(或) 中C语言的getch()函数的功能,为我提供了解决方案?

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() 而您已经编写了一个称为validate()的方法

so change it to 所以将其更改为

onkeypress="validate()";

Remaining seems good, see fiddle 剩下的似乎还不错,看小提琴

Call this function on key press from your html element | 从您的html元素上按下按键时调用此函数| DEMO 演示

Number wil not be accepted and will not be visible in text box 数字不被接受,并且在文本框中将不可见

<input type="text" onkeypress="return checks(this,event)" />

JavaScript 的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/ 在这里运行: http : //jsfiddle.net/edgarinvillegas/XPvU2/1/

Hope this helps. 希望这可以帮助。 Cheers 干杯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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