【问题标题】:How can I restrict textfield [duplicate]如何限制文本字段[重复]
【发布时间】:2013-10-23 01:58:59
【问题描述】:

我想创建 TextField 它只允许数字。为此,我编写了以下代码,但它不起作用。

脚本代码:

 function numberTextField(){
var keyAsciiValue=event.keyCode||event.which;
console.log(keyAsciiValue);
if (keyAsciiValue>=48&&keyAsciiValue<=57) {
    console.log("This is Number");
    return true;
}else{
    console.log("This is Not a Number");
    return false;
};
} 

html代码:

<input type="text" onkeyup="numberTextField()" placeholder="NoOfRows" id="fieldsCount2"/>

谁能帮帮我。

谢谢。

【问题讨论】:

  • @Mr.Alien 你的建议,它工作正常。但我不明白前两行的语法。evt = (evt) ? evt : window.event; var charCode = (evt.which) ? evt.which : evt.keyCode;
  • @Mr.Alien 我喜欢你的建议,但我不能喜欢你的评论。
  • @user2873816 没问题,我也不是 JS foo,所以无法解释那行的意思:)

标签: javascript


【解决方案1】:

更新代码:

<input type="text" value="" onkeypress="this.value = this.value.replace(/[^0-9]$/,'')"  onkeyup="this.value = this.value.replace(/[^0-9]$/,'')" placeholder="NoOfRows" id="fieldsCount2"/>

【讨论】:

  • 不能正常工作,只输入一个字符,马上输入一个数字。
  • 或者只是按任意键,如“a”,不要松开。
  • 感谢您发现故障..检查更新的代码...希望它会改变你的想法。:)
【解决方案2】:
function numberTextField(evt)
{
   var charCode = (evt.which) ? evt.which : event.keyCode
   if (charCode > 31 && (charCode < 48 || charCode > 57))
   {
         console.log("This is Not a Number");
         return false;
   }
   else
   {
          console.log("This is a Number");
          return true;
   }         


} 

和 HTML

<input type="text" onkeypress="return numberTextField(event)" placeholder="NoOfRows" id="fieldsCount2"/>

【讨论】:

  • 你写了 2 个返回语句。retuen true 属于 else 条件
  • 检查编辑后的答案
  • 更新的答案也不起作用。
  • 对不起,我忘了在 onkeypress 中添加 return。现在它应该可以工作了 :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-04-30
  • 1970-01-01
  • 1970-01-01
  • 2019-12-08
  • 1970-01-01
  • 2021-01-21
  • 1970-01-01
相关资源
最近更新 更多