【问题标题】:jQuery input limit numbers/digits to 4, but text can be infinite lengthjQuery 输入限制数字/数字为 4,但文本可以无限长
【发布时间】:2012-06-13 05:18:53
【问题描述】:

如何输入限制为 4 个数字/数字,但如果输入文本,则字符长度是无限的?

最终工作代码:

    function isNumber (o) {
  return ! isNaN (o-0);
}

$("#txt").keyup(function(e){
    txtVal = $(this).val();  
     if(isNumber(txtVal) && txtVal.length>4)
     {
         $(this).val(txtVal.substring(0,4) )
           $(".error").html("4 Numbers Only").show();
      return false;
     }
});
});

【问题讨论】:

    标签: jquery input numbers limit


    【解决方案1】:

    Live Demo

    HTML

     <input id="txt1" type="text" name="usrname" />​
    

    JAVASCRIPT

    function isNumber (o) {
      return ! isNaN (o-0);
    }  
    
    $("#txt1").keyup(function(e){
    txtVal = $(this).val();  
     if(isNumber(txtVal) && txtVal.length>4)
     {
         $(this).val(txtVal.substring(0,4) )
     }
    });
    

    【讨论】:

    • 基本技巧。但这如何回答问题?
    • 如果你重新阅读这个问题,你会得到我的 +1。 (无限文本,但只有 4 位数字。)
    • @Adil 干得好阿迪尔...检查一下,如果用户像这样输入 aaa111111111 并清除所有字符? jsfiddle.net/C4Y99/3
    • 是的@Gopesh,这是可能遇到的场景之一。这可以帮助我们,但取决于我们到底想要什么。 jsfiddle.net/C4Y99/4
    • 感谢@Gopesh 的赞美 :)
    【解决方案2】:

    您可以检查该值是否为数值,当超过 4 个字符时触发验证。

    $("#yourField").change(function(e){
         if(isNaN($(this).val()) && $(this).val().length > 4)
         {
            //trigger validation
         }
    });
    

    【讨论】:

      【解决方案3】:

      HTML

      <input type="text" class="numeric" />
      

      JQUERY

      $('.numeric').keypress(function(e) { 
      
      var verified = (e.which == 8 || e.which == undefined || e.which == 0) ? null : String.fromCharCode(e.which).match(/[^0-9]/);
      if (verified || e.delegateTarget.value.length>3 || e.ctrlKey ==true) { if(e.which!=8 ){e.preventDefault();}}
      
      }).on('paste',function(e){ e.preventDefault();});
      

      工作示例

      http://jsfiddle.net/nadeemmnn2007/C4Y99/52/

      【讨论】:

      • 请查看演示
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-31
      • 1970-01-01
      • 1970-01-01
      • 2013-11-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多