【问题标题】:Restricting input to textbox: allowing only numbers and decimal point限制文本框的输入:只允许数字和小数点
【发布时间】:2010-05-11 05:02:29
【问题描述】:

如何限制文本框的输入,使其只接受数字和小数点?

【问题讨论】:

    标签: javascript html


    【解决方案1】:

    <HTML>
      <HEAD>
        <SCRIPT language=Javascript>
           <!--
           function isNumberKey(evt)
           {
              var charCode = (evt.which) ? evt.which : evt.keyCode;
              if (charCode != 46 && charCode > 31 
                && (charCode < 48 || charCode > 57))
                 return false;
    
              return true;
           }
           //-->
        </SCRIPT>
      </HEAD>
      <BODY>
        <INPUT id="txtChar" onkeypress="return isNumberKey(event)" 
               type="text" name="txtChar">
      </BODY>
    </HTML>

    这真的有效!

    【讨论】:

    • 为什么需要 && charCode >31?
    • 字符 31 是单元分隔符代码。几乎所有的数字和文字都在 32 或更高之间。代码读取如果输入的字符代码不是十进制 AND 大于 31(单位分隔符)但小于 48(数字零)或大于 57(数字九),不接受。
    • if (charCode == 46 && evt.srcElement.value.split('.').length>1) { return false;它将剥夺多个'.'... :)
    • 包括键盘数字键和句点:&amp;&amp; charCode != 190 &amp;&amp; charCode != 110 &amp;&amp; (charCode &gt; 105 || charCode &lt; 96)
    • 我可以在此字段中粘贴非数字字符,是否有任何解决方法/
    【解决方案2】:

    接受的解决方案不完整,因为您可以输入多个“.”,例如 24....22..22。经过一些小的修改,它将按预期工作:

    <html>
    
    <head>
      <script type="text/javascript">
        function isNumberKey(txt, evt) {
          var charCode = (evt.which) ? evt.which : evt.keyCode;
          if (charCode == 46) {
            //Check if the text already contains the . character
            if (txt.value.indexOf('.') === -1) {
              return true;
            } else {
              return false;
            }
          } else {
            if (charCode > 31 &&
              (charCode < 48 || charCode > 57))
              return false;
          }
          return true;
        }
      </script>
    </head>
    
    <body>
      <input type="text" onkeypress="return isNumberKey(this, event);" />
    </body>
    
    </html>

    【讨论】:

    • 我使用了你的答案,但我修改了这个 onkeypress="return isNumberKey(this,event);"
    • 是的,我认为输入传递事件是可选的,因为它适用于两种情况,谢谢
    • 为我们节省了几个键击.. tq
    • 唯一的问题是你可以复制粘贴到文本中。添加到输入元素ondrop="return false;" onpaste="return false;" oncontextmenu="return false;" 似乎就足够了
    • 阻止他们使用拖放或复制粘贴是对每个用户的误用。
    【解决方案3】:
    form.onsubmit = function(){
        return textarea.value.match(/^\d+(\.\d+)?$/);
    }
    

    这是你要找的吗?

    希望对你有帮助。

    编辑:我在上面编辑了我的示例,因此只能有一个句点,前面至少有一个数字,后面至少有一个数字。

    【讨论】:

    • 认为这也将验证 '99.23.65.86' .... 但我想问题是关于用单点验证 '56987.32' .....
    • 我看到发帖人已经编辑了他/她的原始问题。感谢您的更新!
    • 我最好用 /^\d+([\.,]\d+)?$/ 来支持国际号码(这里用逗号代替点)
    【解决方案4】:

    这是另一种解决方案,它允许使用十进制数字并将小数点后的数字限制为 2 位小数。

    function isNumberKey(evt, element) {
      var charCode = (evt.which) ? evt.which : event.keyCode
      if (charCode > 31 && (charCode < 48 || charCode > 57) && !(charCode == 46 || charCode == 8))
        return false;
      else {
        var len = $(element).val().length;
        var index = $(element).val().indexOf('.');
        if (index > 0 && charCode == 46) {
          return false;
        }
        if (index > 0) {
          var CharAfterdot = (len + 1) - index;
          if (CharAfterdot > 3) {
            return false;
          }
        }
    
      }
      return true;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="number" id="rate" placeholder="Billing Rate" required onkeypress="return isNumberKey(event,this)">

    【讨论】:

    • 几乎完美..if 的最后一个条件是缺少大写的“C”。
    • 漂亮的解决方案!!
    • 漂亮。非常适合我。
    • 请注意,当文本被粘贴或拖放到字段上时,此解决方案允许多个点 (.)、破折号 (-) 和字母 e。默认情况下,HTML 元素还将显示两个箭头,用于在 Chrome 中递增和递减数字。递减按钮允许数字低于零。
    • 如果您已经放置了 2 个小数点,此解决方案不允许在左侧输入任何内容,您还必须处理粘贴。
    【解决方案5】:

    这里介绍的所有解决方案都使用单键事件。这很容易出错,因为输入也可以使用 copy'n'paste 或 drag'n'drop 给出。还有一些解决方案限制了非字符键的使用,例如ctrl+cPos1 等。

    我建议不要检查每次按键,而是检查结果是否符合您的期望。

    var validNumber = new RegExp(/^\d*\.?\d*$/);
    var lastValid = document.getElementById("test1").value;
    function validateNumber(elem) {
      if (validNumber.test(elem.value)) {
        lastValid = elem.value;
      } else {
        elem.value = lastValid;
      }
    }
    &lt;textarea id="test1" oninput="validateNumber(this);" &gt;&lt;/textarea&gt;

    oninput 事件在文本区域中的某些内容发生更改之后且在呈现之前触发。

    您可以将 RegEx 扩展为您想要接受的任何数字格式。这比检查单个按键的可维护性和可扩展性要高得多。

    【讨论】:

    • 这是最优雅的解决方案!
    【解决方案6】:

    你在寻找这样的东西吗?

       <HTML>
       <HEAD>
       <SCRIPT language=Javascript>
          <!--
          function isNumberKey(evt)
          {
             var charCode = (evt.which) ? evt.which : event.keyCode
             if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
                return false;
    
             return true;
          }
          //-->
       </SCRIPT>
       </HEAD>
       <BODY>
          <INPUT id="txtChar" onkeypress="return isNumberKey(event)" type="text" name="txtChar">
       </BODY>
      </HTML>
    

    【讨论】:

      【解决方案7】:

      只需在 Jquery 中应用此方法,您就可以验证您的文本框是否只接受带小数的数字。

      function IsFloatOnly(element) {    
      var value = $(element).val(); 
      var regExp ="^\\d+(\\.\\d+)?$";
      return value.match(regExp); 
      }
      

      请看工作演示here

      【讨论】:

        【解决方案8】:

        这是 cas 可以帮助您的脚本:

        <script type="text/javascript">
        // price text-box allow numeric and allow 2 decimal points only
        function extractNumber(obj, decimalPlaces, allowNegative)
        {
            var temp = obj.value;
        
            // avoid changing things if already formatted correctly
            var reg0Str = '[0-9]*';
            if (decimalPlaces > 0) {
                reg0Str += '\[\,\.]?[0-9]{0,' + decimalPlaces + '}';
            } else if (decimalPlaces < 0) {
                reg0Str += '\[\,\.]?[0-9]*';
            }
            reg0Str = allowNegative ? '^-?' + reg0Str : '^' + reg0Str;
            reg0Str = reg0Str + '$';
            var reg0 = new RegExp(reg0Str);
            if (reg0.test(temp)) return true;
        
            // first replace all non numbers
            var reg1Str = '[^0-9' + (decimalPlaces != 0 ? '.' : '') + (decimalPlaces != 0 ? ',' : '') + (allowNegative ? '-' : '') + ']';
            var reg1 = new RegExp(reg1Str, 'g');
            temp = temp.replace(reg1, '');
        
            if (allowNegative) {
                // replace extra negative
                var hasNegative = temp.length > 0 && temp.charAt(0) == '-';
                var reg2 = /-/g;
                temp = temp.replace(reg2, '');
                if (hasNegative) temp = '-' + temp;
            }
        
            if (decimalPlaces != 0) {
                var reg3 = /[\,\.]/g;
                var reg3Array = reg3.exec(temp);
                if (reg3Array != null) {
                    // keep only first occurrence of .
                    //  and the number of places specified by decimalPlaces or the entire string if decimalPlaces < 0
                    var reg3Right = temp.substring(reg3Array.index + reg3Array[0].length);
                    reg3Right = reg3Right.replace(reg3, '');
                    reg3Right = decimalPlaces > 0 ? reg3Right.substring(0, decimalPlaces) : reg3Right;
                    temp = temp.substring(0,reg3Array.index) + '.' + reg3Right;
                }
            }
        
            obj.value = temp;
        }
        function blockNonNumbers(obj, e, allowDecimal, allowNegative)
        {
            var key;
            var isCtrl = false;
            var keychar;
            var reg;
            if(window.event) {
                key = e.keyCode;
                isCtrl = window.event.ctrlKey
            }
            else if(e.which) {
                key = e.which;
                isCtrl = e.ctrlKey;
            }
        
            if (isNaN(key)) return true;
        
            keychar = String.fromCharCode(key);
        
            // check for backspace or delete, or if Ctrl was pressed
            if (key == 8 || isCtrl)
            {
                return true;
            }
        
            reg = /\d/;
            var isFirstN = allowNegative ? keychar == '-' && obj.value.indexOf('-') == -1 : false;
            var isFirstD = allowDecimal ? keychar == '.' && obj.value.indexOf('.') == -1 : false;
            var isFirstC = allowDecimal ? keychar == ',' && obj.value.indexOf(',') == -1 : false;
            return isFirstN || isFirstD || isFirstC || reg.test(keychar);
        }
        function blockInvalid(obj)
        {
            var temp=obj.value;
            if(temp=="-")
            {
                temp="";
            }
        
            if (temp.indexOf(".")==temp.length-1 && temp.indexOf(".")!=-1)
            {
                temp=temp+"00";
            }
            if (temp.indexOf(".")==0)
            {
                temp="0"+temp;
            }
            if (temp.indexOf(".")==1 && temp.indexOf("-")==0)
            {
                temp=temp.replace("-","-0") ;
            }
            if (temp.indexOf(",")==temp.length-1 && temp.indexOf(",")!=-1)
            {
                temp=temp+"00";
            }
            if (temp.indexOf(",")==0)
            {
                temp="0"+temp;
            }
            if (temp.indexOf(",")==1 && temp.indexOf("-")==0)
            {
                temp=temp.replace("-","-0") ;
            }
            temp=temp.replace(",",".") ;
            obj.value=temp;
        }
        // end of price text-box allow numeric and allow 2 decimal points only
        </script>
        
        <input type="Text" id="id" value="" onblur="extractNumber(this,2,true);blockInvalid(this);" onkeyup="extractNumber(this,2,true);" onkeypress="return blockNonNumbers(this, event, true, true);">
        

        【讨论】:

          【解决方案9】:

          对于像我一样在这里磕磕绊绊的任何人,这是我编写的一个 jQuery 1.10.2 版本,虽然资源密集,但对我来说效果很好:

          /***************************************************
          * Only allow numbers and one decimal in text boxes
          ***************************************************/
          $('body').on('keydown keyup keypress change blur focus paste', 'input[type="text"]', function(){
              var target = $(this);
          
              var prev_val = target.val();
          
              setTimeout(function(){
                  var chars = target.val().split("");
          
                  var decimal_exist = false;
                  var remove_char = false;
          
                  $.each(chars, function(key, value){
                      switch(value){
                          case '0':
                          case '1':
                          case '2':
                          case '3':
                          case '4':
                          case '5':
                          case '6':
                          case '7':
                          case '8':
                          case '9':
                          case '.':
                              if(value === '.'){
                                  if(decimal_exist === false){
                                      decimal_exist = true;
                                  }
                                  else{
                                      remove_char = true;
                                      chars[''+key+''] = '';
                                  }
                              }
                              break;
                          default:
                              remove_char = true;
                              chars[''+key+''] = '';
                              break;
                      }
                  });
          
                  if(prev_val != target.val() && remove_char === true){
                      target.val(chars.join(''))
                  }
              }, 0);
          });
          

          【讨论】:

            【解决方案10】:

            对@rebisco 完美验证小数的绝妙答案的小修正。

            function isNumberKey(evt) {
                debugger;
                var charCode = (evt.which) ? evt.which : event.keyCode;
                if (charCode == 46 && evt.srcElement.value.split('.').length>1) {
                    return false;
                }
                if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
                    return false;
                return true;
            }
            

            【讨论】:

            • 这很好。但是,我想将其限制为小数点后 2 位,无论如何要这样做?
            【解决方案11】:

            如果你想要浮点值,

            这是我正在使用的功能

            <HTML>
            
            <HEAD>
              <SCRIPT language=Javascript>
                <!--
                function check(e, value) {
                  //Check Charater
                  var unicode = e.charCode ? e.charCode : e.keyCode;
                  if (value.indexOf(".") != -1)
                    if (unicode == 46) return false;
                  if (unicode != 8)
                    if ((unicode < 48 || unicode > 57) && unicode != 46) return false;
                }
                //-->
              </SCRIPT>
            </HEAD>
            
            <BODY>
              <INPUT id="txtChar" onkeypress="return check(event,value)" type="text" name="txtChar">
            </BODY>
            
            </HTML>

            【讨论】:

              【解决方案12】:
                function onlyDotsAndNumbers(txt, event) {
                      var charCode = (event.which) ? event.which : event.keyCode
                      if (charCode == 46) {
                          if (txt.value.indexOf(".") < 0)
                              return true;
                          else
                              return false;
                      }
              
                      if (txt.value.indexOf(".") > 0) {
                          var txtlen = txt.value.length;
                          var dotpos = txt.value.indexOf(".");
                          //Change the number here to allow more decimal points than 2
                          if ((txtlen - dotpos) > 2)
                              return false;
                      }
              
                      if (charCode > 31 && (charCode < 48 || charCode > 57))
                          return false;
              
                      return true;
                  }
              
              
              <input type="text" id="txtAmount" onkeypress="return onlyDotsAndNumbers(this,event);" maxlength="10" oncopy="return false" ondrag="return false" ondrop="return false" onpaste="return false" />
              

              只有数字,一位小数,不能复制粘贴。

              【讨论】:

                【解决方案13】:
                inputelement.onchange= inputelement.onkeyup= function isnumber(e){
                    e= window.event? e.srcElement: e.target;
                    while(e.value && parseFloat(e.value)+''!= e.value){
                            e.value= e.value.slice(0, -1);
                    }
                }
                

                【讨论】:

                  【解决方案14】:
                  function integerwithdot(s, iid){
                          var i;
                          s = s.toString();
                          for (i = 0; i < s.length; i++){
                              var c;
                              if (s.charAt(i) == ".") {
                              } else {
                                  c = s.charAt(i);
                              }
                              if (isNaN(c)) {
                                  c = "";
                                  for(i=0;i<s.length-1;i++){
                                      c += s.charAt(i);
                                  }
                                  document.getElementById(iid).value = c;
                                  return false;
                              }
                          }
                          return true;
                      }
                  

                  【讨论】:

                    【解决方案15】:

                    假设您的文本框字段名称是Income
                    当你需要验证你的字段时调用这个 validate 方法:

                    function validate() {
                        var currency = document.getElementById("Income").value;
                          var pattern = /^[1-9]\d*(?:\.\d{0,2})?$/ ;
                        if (pattern.test(currency)) {
                            alert("Currency is in valid format");
                            return true;
                        } 
                            alert("Currency is not in valid format!Enter in 00.00 format");
                            return false;
                    }
                    

                    【讨论】:

                      【解决方案16】:

                      扩展@rebisco 的答案。下面的代码将只允许文本框中的数字和单个“.”(句点)。

                      function isNumberKey(evt) {
                              var charCode = (evt.which) ? evt.which : event.keyCode;
                              if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
                                  return false;
                              } else {
                                  // If the number field already has . then don't allow to enter . again.
                                  if (evt.target.value.search(/\./) > -1 && charCode == 46) {
                                      return false;
                                  }
                                  return true;
                              }
                          }
                      

                      【讨论】:

                        【解决方案17】:

                        限制输入到文本框的替代方法,以便它只接受数字并且小数点是 在 html 输入中使用 javascript。这对我有用:

                        <input type="text" class="form-control" id="price" name="price" placeholder="Price" 
                        vrequired onkeyup="this.value=this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1')">
                        

                        --接受--

                        9

                        9.99

                        --不接受--

                        9.99.99

                        ABC

                        【讨论】:

                          【解决方案18】:

                          更好的解决方案

                          var checkfloats = function(event){
                              var charCode = (event.which) ? event.which : event.keyCode;
                              if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
                                  return false;
                          
                              if(event.target.value.indexOf('.') >=0 && charCode == 46)
                                  return false;
                          
                              return true;
                          }
                          

                          【讨论】:

                            【解决方案19】:

                            我选择在 oninput 事件中解决此问题,以便处理键盘粘贴、鼠标粘贴和击键问题。传递 true 或 false 以指示十进制或整数验证。

                            基本上是三个一班的三个步骤。如果您不想截断小数,请评论第三步。第三步也可以进行四舍五入的调整。

                            // Example Decimal usage;
                            // <input type="text"  oninput="ValidateNumber(this, true);" />
                            // Example Integer usage:
                            // <input type="text"  oninput="ValidateNumber(this, false);" />
                            function ValidateNumber(elm, isDecimal) {
                                try {
                            
                                    // For integers, replace everything except for numbers with blanks.
                                    if (!isDecimal) 
                                        elm.value = elm.value.replace(/[^0-9]/g, ''); 
                                    else {
                                        // 1. For decimals, replace everything except for numbers and periods with blanks.
                                        // 2. Then we'll remove all leading ocurrences (duplicate) periods
                                        // 3. Then we'll chop off anything after two decimal places.
                            
                                        // 1. replace everything except for numbers and periods with blanks.
                                        elm.value = elm.value.replace(/[^0-9.]/g, '');
                            
                                        //2. remove all leading ocurrences (duplicate) periods
                                        elm.value = elm.value.replace(/\.(?=.*\.)/g, '');
                            
                                        // 3. chop off anything after two decimal places.
                                        // In comparison to lengh, our index is behind one count, then we add two for our decimal places.
                                        var decimalIndex = elm.value.indexOf('.');
                                        if (decimalIndex != -1) { elm.value = elm.value.substr(0, decimalIndex + 3); }
                                    }
                                }
                                catch (err) {
                                    alert("ValidateNumber " + err);
                                }
                            }
                            

                            【讨论】:

                              【解决方案20】:

                              从@rebisco 回答开始:

                              function count_appearance(mainStr, searchFor) {
                                  return (mainStr.split(searchFor).length - 1);
                              }
                              function isNumberKey(evt)
                              {
                                  $return = true;
                                  var charCode = (evt.which) ? evt.which : event.keyCode;
                                  if (charCode != 46 && charCode > 31
                                          && (charCode < 48 || charCode > 57))
                                      $return = false;
                                  $val = $(evt.originalTarget).val();
                                  if (charCode == 46) {
                                      if (count_appearance($val, '.') > 0) {
                                          $return = false;
                                      }
                                      if ($val.length == 0) {
                                          $return = false;
                                      }
                                  }
                                  return $return;
                              }
                              

                              只允许这种格式:123123123[.121213]

                              在这里演示demo

                              【讨论】:

                                【解决方案21】:

                                希望它对你有用。

                                <input type="text" onkeypress="return chkNumeric(event)" />
                                
                                <script>
                                    function chkNumeric(evt) {
                                        evt = (evt) ? evt : window.event;
                                        var charCode = (evt.which) ? evt.which : evt.keyCode;
                                        if (charCode > 31 && (charCode < 48 || charCode > 57)) {
                                            if (charCode == 46) { return true; }
                                            else { return false; }
                                        }
                                        return true;
                                    }
                                </script>
                                

                                【讨论】:

                                  【解决方案22】:

                                  以下代码对我有用

                                  带有“onkeypress”事件的输入框如下

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

                                  isNumberKey函数如下

                                  function isNumberKey(txt, evt) {
                                    var charCode = (evt.which) ? evt.which : evt.keyCode;
                                    if (charCode == 46) {
                                      //Check if the text already contains the . character
                                      if (txt.value.indexOf('.') === -1) {
                                          return true;
                                      } else {
                                          return false;
                                      }
                                    } else {
                                      if (charCode > 31 && (charCode < 48 || charCode > 57))
                                          return false;
                                    }
                                    return true;
                                  }

                                  【讨论】:

                                    【解决方案23】:

                                    我观察到,对于此处提供的所有答案,如果我们在文本框中选择文本的某些部分并尝试覆盖该部分,则事情将无法正常工作。 所以我修改了如下函数:

                                        <HTML>
                                      <HEAD>
                                        <SCRIPT language=Javascript>
                                           <!--
                                           function isNumberKey(evt)
                                           {
                                             var charCode = (evt.which) ? evt.which : event.keyCode;
                                    
                                    if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
                                    {
                                            return false;
                                    }
                                     if (charCode == 46 && evt.srcElement.value.split('.').length>1 )
                                        {
                                    
                                            return false;
                                    
                                        } 
                                    
                                     if(evt.srcElement.selectionStart<evt.srcElement.selectionEnd)
                                        {
                                              return true;
                                        }
                                    
                                      if(evt.srcElement.value.split('.').length>1 && evt.srcElement.value.split('.')[1].length==2)
                                      {
                                    
                                         return false;
                                      }
                                    
                                    
                                        return true;
                                           }
                                    
                                    
                                           //-->
                                        </SCRIPT>
                                      </HEAD>
                                      <BODY>
                                        <INPUT id="txtChar" onkeypress="return isNumberKey(event)" 
                                               type="text" name="txtChar">
                                      </BODY>
                                    </HTML>
                                    

                                    【讨论】:

                                      【解决方案24】:

                                      对于十进制数,并且还允许在点后有 2 位小数的负数...我将函数修改为:

                                      <input type="text" id="txtSample" onkeypress="return isNumberKey(event,this)"/>
                                      
                                      
                                      
                                      function isNumberKey(evt, element){
                                      
                                              var charCode = (evt.which) ? evt.which : event.keyCode
                                              if (charCode > 31 && (charCode < 48 || charCode > 57) && !(charCode == 46 || charCode == 8 || charCode == 45))
                                                  return false;
                                              else {
                                                  var len = $(element).val().length;
                                      
                                                  // Validation Point
                                                  var index = $(element).val().indexOf('.');
                                                  if ((index > 0 && charCode == 46) || len == 0 && charCode == 46) {
                                                      return false;
                                                  }
                                                  if (index > 0) {
                                                      var CharAfterdot = (len + 1) - index;
                                                      if (CharAfterdot > 3) {
                                                          return false;
                                                      }
                                                  }
                                      
                                                  // Validating Negative sign
                                                  index = $(element).val().indexOf('-');
                                                  if ((index > 0 && charCode == 45) || (len > 0 && charCode == 45)) {
                                                      return false;
                                                  }
                                              }
                                              return true;
                                          }
                                      

                                      【讨论】:

                                        【解决方案25】:
                                        <input type="text" class="number_only" />    
                                        <script>
                                        $(document).ready(function() {
                                            $('.number_only').keypress(function (event) {
                                                return isNumber(event, this)
                                            });        
                                        });
                                        
                                        function isNumber(evt, element) {
                                            var charCode = (evt.which) ? evt.which : event.keyCode
                                        
                                            if ((charCode != 45 || $(element).val().indexOf('-') != -1) && (charCode != 46 || $(element).val().indexOf('.') != -1) && ((charCode < 48 && charCode != 8) || charCode > 57)){
                                                return false;
                                            }
                                            else {
                                                return true;
                                            }
                                        } 
                                        </script>
                                        

                                        http://www.encodedna.com/2013/05/enter-only-numbers-using-jquery.htm

                                        【讨论】:

                                          【解决方案26】:
                                          function isNumberKey(evt)
                                          {
                                              var charCode = (evt.which) ? evt.which : evt.keyCode;
                                          
                                              if(charCode==8 || charCode==13|| charCode==99|| charCode==118 || charCode==46)
                                              {    
                                                  return true;  
                                              }
                                          
                                              if (charCode > 31 && (charCode < 48 || charCode > 57))
                                              {   
                                                  return false; 
                                              }
                                              return true;
                                          }
                                          

                                          它将只允许数字,并允许您输入“。”为十进制。

                                          【讨论】:

                                            【解决方案27】:
                                            <script type="text/javascript">
                                            
                                                function isNumberKey(evt) {
                                                    var charCode = (evt.which) ? evt.which : event.keyCode;
                                                    if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
                                                        return false;
                                            
                                                    return true;
                                                }
                                            
                                            </script>
                                            

                                            @Html.EditorFor(model => model.Orderids, new { id = "Orderids", Onkeypress=isNumberKey(event)})
                                            

                                            这很好用。

                                            【讨论】:

                                              【解决方案28】:

                                              使用纯 Javascript 示例的最佳且有效的解决方案 现场演示:https://jsfiddle.net/manoj2010/ygkpa89o/

                                              <script>
                                              function removeCommas(nStr) {
                                                  if (nStr == null || nStr == "")
                                                      return ""; 
                                                  return nStr.toString().replace(/,/g, "");
                                              }
                                              
                                              function NumbersOnly(myfield, e, dec,neg)
                                              {        
                                                  if (isNaN(removeCommas(myfield.value)) && myfield.value != "-") {
                                                      return false;
                                                  }
                                                  var allowNegativeNumber = neg || false;
                                                  var key;
                                                  var keychar;
                                              
                                                  if (window.event)
                                                      key = window.event.keyCode;
                                                  else if (e)
                                                      key = e.which;
                                                  else
                                                      return true;
                                                  keychar = String.fromCharCode(key);
                                                  var srcEl = e.srcElement ? e.srcElement : e.target;    
                                                  // control keys
                                                  if ((key == null) || (key == 0) || (key == 8) ||
                                                              (key == 9) || (key == 13) || (key == 27))
                                                      return true;
                                              
                                                  // numbers
                                                  else if ((("0123456789").indexOf(keychar) > -1))
                                                      return true;
                                              
                                                  // decimal point jump
                                                  else if (dec && (keychar == ".")) {
                                                      //myfield.form.elements[dec].focus();
                                                      return srcEl.value.indexOf(".") == -1;        
                                                  }
                                              
                                                  //allow negative numbers
                                                  else if (allowNegativeNumber && (keychar == "-")) {    
                                                      return (srcEl.value.length == 0 || srcEl.value == "0.00")
                                                  }
                                                  else
                                                      return false;
                                              }
                                              </script>
                                              <input name="txtDiscountSum" type="text" onKeyPress="return NumbersOnly(this, event,true)" /> 

                                              【讨论】:

                                                【解决方案29】:

                                                我自己正在解决这个问题,这就是我到目前为止所得到的。这或多或少有效,但由于新的值检查,之后不可能添加减号。也不允许逗号作为千位分隔符,只能使用小数。

                                                它并不完美,但可能会提供一些想法。

                                                app.directive('isNumber', function () {
                                                            return function (scope, elem, attrs) {
                                                                elem.bind('keypress', function (evt) {
                                                                    var keyCode = (evt.which) ? evt.which : event.keyCode;
                                                                    var testValue = (elem[0].value + String.fromCharCode(keyCode) + "0").replace(/ /g, ""); //check ignores spaces
                                                                    var regex = /^\-?\d+((\.|\,)\d+)?$/;                        
                                                                    var allowedChars = [8,9,13,27,32,37,39,44,45, 46] //control keys and separators             
                                                
                                                                   //allows numbers, separators and controll keys and rejects others
                                                                    if ((keyCode > 47 && keyCode < 58) || allowedChars.indexOf(keyCode) >= 0) {             
                                                                        //test the string with regex, decline if doesn't fit
                                                                        if (elem[0].value != "" && !regex.test(testValue)) {
                                                                            event.preventDefault();
                                                                            return false;
                                                                        }
                                                                        return true;
                                                                    }
                                                                    event.preventDefault();
                                                                    return false;
                                                                });
                                                            };
                                                        });
                                                

                                                允许:

                                                11 11 .245(在控制器中模糊为 1111.245)

                                                11,44

                                                -123.123

                                                -1 014

                                                0123(格式模糊为 123)

                                                不允许:

                                                !@#$/*

                                                abc

                                                11.11.1

                                                11,11.1

                                                .42

                                                【讨论】:

                                                  【解决方案30】:
                                                  <input type="text" onkeypress="return isNumberKey(event,this)">
                                                  
                                                  <script>
                                                     function isNumberKey(evt, obj) {
                                                  
                                                              var charCode = (evt.which) ? evt.which : event.keyCode
                                                              var value = obj.value;
                                                              var dotcontains = value.indexOf(".") != -1;
                                                              if (dotcontains)
                                                                  if (charCode == 46) return false;
                                                              if (charCode == 46) return true;
                                                              if (charCode > 31 && (charCode < 48 || charCode > 57))
                                                                  return false;
                                                              return true;
                                                          }
                                                  
                                                  
                                                  </script>
                                                  

                                                  【讨论】:

                                                    猜你喜欢
                                                    • 1970-01-01
                                                    • 2012-03-01
                                                    • 1970-01-01
                                                    • 1970-01-01
                                                    • 1970-01-01
                                                    • 1970-01-01
                                                    • 2010-10-27
                                                    • 2013-04-12
                                                    • 1970-01-01
                                                    相关资源
                                                    最近更新 更多