【问题标题】:javascript input allowing only numbersjavascript输入只允许数字
【发布时间】:2013-01-29 14:37:49
【问题描述】:

我使用这个代码,它可以工作

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

但我无法访问 html,并且只有 javascript

document.getElementById("txtChar").addEventListener("keypress", <<your code>>, false);

应该有什么&lt;&lt;your code&gt;&gt;?

附言发现此组件的另一个错误:
当您复制粘贴(ctrl-v 或右键单击粘贴)时,它不起作用
有人知道怎么解决吗

【问题讨论】:

    标签: javascript


    【解决方案1】:

    如果您喜欢使用HTML5 并且只针对现代浏览器,那么required 和pattern 的新属性就在这里为您服务。示例:

    <input id="txtChar" type="number" required pattern="\d+"/>
    

    你可以通过 CSS 来处理状态,比如

    #txtChar:required:valid {
        border: 1px solid green;
    }
    
    #txtChar:required:invalid {
        border: 1px solid red;
    }
    

    如果在&lt;form&gt; 标记中使用,用户将无法在无效 状态下提交。


    我刚刚读到您无权访问标记,因此深表歉意。我将其作为参考答案。

    【讨论】:

      【解决方案2】:

      在&lt;&lt;your code&gt;&gt; 中添加处理它的函数名称,在这种情况下为isNumberKey;你还需要在return false;之前添加evt.preventDefault();

      下面的这个函数只接受0到9的数字对应的代码,忽略点(“.”)、连字符(“-”)和减号(“-”)。

      function isNumberKey(evt){
          var charCode = (evt.which) ? evt.which : evt.keyCode;
          if (charCode == 46 || charCode > 31 && (charCode < 48 || charCode > 57)){
              evt.preventDefault();
              return false;
          }
          return true;
      }
      

      为 HTML5 浏览器配置输入字段:

      txtChar = document.getElementById("txtChar")
      txtChar.addEventListener("keypress", isNumberKey, false);
      
      //Attributes
      txtChar.type = "number";
      txtChar.min = 0;
      txtChar.pattern = "\\d+";
      txtChar.placeholder = "Only integer positive numbers";
      txtChar.required = "required";
      

      工作示例,包括来自 jAndy 答案的样式:http://jsfiddle.net/pL9Zk/

      【讨论】:

        【解决方案3】:

        是不是搞错了?

        document.getElementById(**"txtChar"**).addEventListener("keypress", function(){
                        return isNumberKey(event);
                    }, false);
        

        【讨论】:

          【解决方案4】:

          事件在函数内部未知。所以提到要运行的事件对象:

          document.getElementById("myElement").addEventListener("keypress", function(event){ 返回 isNumberKey(事件); }, 错误的);

          编辑: 问题有点变化,所以引用答案:
          1.将“myElement”改为“txtChar”
          2. 包含事件对象作为参数

          document.getElementById("txtChar").addEventListener("keypress", function(event){
                              return isNumberKey(event);
                          }, false);
          

          【讨论】:

          • 你是对的,但这不是问题,你的代码不起作用
          • 不要寻找语法问题
          • 在 html 中添加 > 时,当函数返回 false 时,符号不会添加到输入中,但是当我使用 addEventListener 时,函数返回 false,但添加了符号
          • 需要建议 html+javascript Jedi
          【解决方案5】:

          试试这个代码兄弟。我希望它会帮助你很多我使用jQUERY。

          <head>
            <script src="//code.jquery.com/jquery-1.10.2.js"></script>
          </head>
          <body>
          
          
          <input id="txtChar" type="text" name="txtChar">
          
          </body>
          
          
          <script>
          
              $("#txtChar").keypress(function(e) {
                 var charCode = (e.which) ? e.which : event.keyCode;
                    if (charCode != 46 && charCode > 31 
                      && (charCode < 48 || charCode > 57))
                       return false;
          
                    return true;
              });
          
          </script>
          

          【讨论】:

            【解决方案6】:

            如果您不能使用 HTML5 &lt;input type="number"&gt;,那么我将正则表达式输入值,只允许数字。我修改了我编写的脚本来完成类似的任务。它允许粘贴和剥离任何非整数字符。

            var arrowKeys = [37, 38, 39, 40];  
            
            function stripChars( e ) {
              // Don't execute anything if the user is just moving the cursor around and
              // not really entering anything new.
              if(arrowKeys.indexOf(e.keyCode) !== -1){ return; }
            
              var elem = e.currentTarget,
                  cursorPos = elem.selectionEnd;
            
              // strip any unwanted character and assign the value back
              elem.value =  elem.value.replace(/\D/g,'');
              // this avoids the cursor shifting to the end of the input 
              // when inserting an integer in the middle of an already existing number
              elem.selectionEnd = cursorPos;
              elem.focus();
            }
            
            var elem = document.getElementById('elem');
            
            elem.addEventListener('keyup', stripChars, false); 
            elem.addEventListener('paste', stripChars, false); 
            

            不管怎样,你可以查看带有测试的原始脚本here和上面代码的演示here。

            【讨论】:

              【解决方案7】:

              我知道我参加聚会有点晚了。

              jAndy 的 HTML5 示例可能是支持它的浏览器的最佳答案。 Josaph 的 JavaScript 回答也很好,因为它启发了我解决提问者的附录和我的问题的答案。

              以下内容会丢弃与正则表达式匹配的输入(不是数字,替换为空字符串),并在有输入时调用,即使来自粘贴。

               function stripNonNumeric() {
                 this.value = this.value.replace(/\D+/g, '');
               }
              
               var txtChar = document.getElementById("txtChar");
               if (txtChar.addEventListener) {
                 txtChar.addEventListener("input", stripNonNumeric);
               } else if (txtChar.attachEvent) {
                 txtChar.attachEvent("oninput", stripNonNumeric);
               }
              

              我不是 JavaScript 专家,我不确定这是否是解决问题的好方法,或者是否需要考虑性能问题。但是,它对我有用。

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2012-10-08
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2014-09-14
                • 2017-08-11
                • 1970-01-01
                相关资源
                最近更新 更多