【问题标题】:jquery only allow input float numberjquery 只允许输入浮点数
【发布时间】:2011-06-21 07:13:14
【问题描述】:

我正在制作一些只允许浮点数的输入掩码。但目前的问题是我无法检查是否输入了多个点。你能帮我检查一下这些点并阻止它吗?

直播代码:http://jsfiddle.net/thisizmonster/VRa6n/

$('.number').keypress(function(event) {
    if (event.which != 46 && (event.which < 47 || event.which > 59))
    {
        event.preventDefault();
        if ((event.which == 46) && ($(this).indexOf('.') != -1)) {
            event.preventDefault();
        }
    }
});

【问题讨论】:

标签: jquery validation


【解决方案1】:

您可以在同一条语句中检查期间。

另外,你需要使用val方法来获取元素的值。

另外,您要检查区间 48 到 57,而不是 47 到 59,否则您还将允许 /:;

$('.number').keypress(function(event) {
  if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
    event.preventDefault();
  }
});

【讨论】:

  • 但是如果第一个符号是点怎么办?
  • @user2167382:如果您指定不允许这样做,这只是一个问题。将'.42' 之类的字符串解析为浮点数就可以了。句号前的零是科学记数法(当然句号后面有数字就行)。
  • @RohitSutharYiiExpert:你可以在条件中添加`&& event.which != 8`来解决这个问题。
  • @Guffa 谢谢,在复制粘贴的情况下呢??
  • @RohitSutharYiiExpert:那个键也有特定的键码,但我认为你应该检查你想要禁止的字符而不是允许的字符。
【解决方案2】:

我认为你们错过了左右箭头、删除和退格键。

 $('.number').keypress(function(event) {

     if(event.which == 8 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 46) 
          return true;

     else if((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57))
          event.preventDefault();

});

【讨论】:

  • 你的 else if 条件错误,允许输入几个点。应该是if(event.which == 46 &amp;&amp; $(this).val().indexOf('.') != -1) { event.preventDefault(); }
  • 它还允许% and '
  • 它还允许 % 和 '
【解决方案3】:

我想每个人都忘记了用鼠标粘贴文本的情况,在这种情况下你无法检测到击键,因为没有。这是我一直在研究的另一种方法。

// only integer or float numbers (with precision limit)
// example element: <input type="text" value="" class="number" name="number" id="number" placeholder="enter number" />

$('.number').on('keydown keypress keyup paste input', function () {

    // allows 123. or .123 which are fine for entering on a MySQL decimal() or float() field
    // if more than one dot is detected then erase (or slice) the string till we detect just one dot
    // this is likely the case of a paste with the right click mouse button and then a paste (probably others too), the other situations are handled with keydown, keypress, keyup, etc

    while ( ($(this).val().split(".").length - 1) > 1 ) {

        $(this).val($(this).val().slice(0, -1));

        if ( ($(this).val().split(".").length - 1) > 1 ) {
            continue;
        } else {
            return false;
        }

    }

    // replace any character that's not a digit or a dot

    $(this).val($(this).val().replace(/[^0-9.]/g, ''));

    // now cut the string with the allowed number for the integer and float parts
    // integer part controlled with the int_num_allow variable
    // float (or decimal) part controlled with the float_num_allow variable

    var int_num_allow = 3;
    var float_num_allow = 1;

    var iof = $(this).val().indexOf(".");

    if ( iof != -1 ) {

        // this case is a mouse paste (probably also other events) with more numbers before the dot than is allowed
        // the number can't be "sanitized" because we can't "cut" the integer part, so we just empty the element and optionally change the placeholder attribute to something meaningful

        if ( $(this).val().substring(0, iof).length > int_num_allow ) {
            $(this).val('');
            // you can remove the placeholder modification if you like
            $(this).attr('placeholder', 'invalid number');
        }

        // cut the decimal part

        $(this).val($(this).val().substring(0, iof + float_num_allow + 1));

    } else {

        $(this).val($(this).val().substring(0, int_num_allow));

    }

    return true;

});

【讨论】:

  • 很好也很简单。您只需更改您的正则表达式,也将适用于其他验证。伟大的工作伙伴。
【解决方案4】:

适用于整数和浮点值。另外,复制/粘贴剪贴板事件。

var el = $('input[name="numeric"]');
el.prop("autocomplete",false); // remove autocomplete (optional)
el.on('keydown',function(e){
	var allowedKeyCodesArr = [9,96,97,98,99,100,101,102,103,104,105,48,49,50,51,52,53,54,55,56,57,8,37,39,109,189,46,110,190];  // allowed keys
	if($.inArray(e.keyCode,allowedKeyCodesArr) === -1 && (e.keyCode != 17 && e.keyCode != 86)){  // if event key is not in array and its not Ctrl+V (paste) return false;
		e.preventDefault();
	} else if($.trim($(this).val()).indexOf('.') > -1 && $.inArray(e.keyCode,[110,190]) != -1){  // if float decimal exists and key is not backspace return fasle;
		e.preventDefault();
	} else {
		return true;
	};  
}).on('paste',function(e){  // on paste
	var pastedTxt = e.originalEvent.clipboardData.getData('Text').replace(/[^0-9.]/g, '');  // get event text and filter out letter characters
	if($.isNumeric(pastedTxt)){  // if filtered value is numeric
		e.originalEvent.target.value = pastedTxt;
		e.preventDefault();
	} else {  // else 
		e.originalEvent.target.value = ""; // replace input with blank (optional)
		e.preventDefault();  // retur false
	};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" name="numeric" value="" placeholder="insert value">

[2017-10-31] Vanilla.js

let el = document.querySelector('input[name="numeric"]');
el.addEventListener('keypress',(event) => {
  let k = event.key,
      t = isNaN(k),
      sc = ['Backspace'].indexOf(k) === -1,
      d = k === '.',dV = el.value.indexOf('.') > -1,
      m = k === '-',mV = el.value.length > 0;

      if((t && sc) && ((d && dV) || (m && dV) || (m && mV) || ((t && !d) && (t && !m)))){event.preventDefault();}
},false);
el.addEventListener('paste',(event) => {
    if(event.clipboardData.types.indexOf('text/html') > -1){
        if(isNaN(event.clipboardData.getData('text'))){event.preventDefault();}
    }
},false);
&lt;input type="text" name="numeric"&gt;

【讨论】:

  • 现在可以了 :) 。只需将 keyCodes 删除或添加到 allowedKeyCodesArr var。
  • 它确实允许 3453。如果没有输入小数点后的数字。它应该检查模糊并且不应该允许。
【解决方案5】:

您的代码看起来不错,但过于复杂。

首先是$(this).val().indexOf,因为你想用这个值做点什么。

其次,event.which == 46 检查位于 if 子句中,该子句仅在 event.which != 46 时通过,这永远不会为真。

我最终得到了这个可行的方法:http://jsfiddle.net/VRa6n/3/

$('.number').keypress(function(event) {
    if(event.which < 46
    || event.which > 59) {
        event.preventDefault();
    } // prevent if not number/dot

    if(event.which == 46
    && $(this).val().indexOf('.') != -1) {
        event.preventDefault();
    } // prevent if already dot
});

【讨论】:

  • event.which 为 .在 Mac 上是 190。
  • 如何删除输入的数字?
【解决方案6】:

另一个插件,基于 Carlos Castillo 的回答

https://github.com/nikita-vanyasin/jquery.numberfield.js

为 jQuery 对象添加方法:

$('input.my_number_field').numberField(options);

选项在哪里(您可以传递任何选项或不传递选项):

{
    ints: 2, // digits count to the left from separator
    floats: 6, // digits count to the right from separator
    separator: "."
}

【讨论】:

    【解决方案7】:

    我找到了这种方法,

    $.validator.addMethod("currency", function (value, element) {
      return this.optional(element) || /^\$(\d{1,3}(\,\d{3})*|(\d+))(\.\d{2})?$/.test(value);
    }, "Please specify a valid amount");
    

    https://gist.github.com/jonkemp/9094324

    【讨论】:

      【解决方案8】:

      HTML

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

      Javascript

      function isFloatNumber(item,evt) {
          evt = (evt) ? evt : window.event;
          var charCode = (evt.which) ? evt.which : evt.keyCode;
          if (charCode==46)
          {
              var regex = new RegExp(/\./g)
              var count = $(item).val().match(regex).length;
              if (count > 1)
              {
                  return false;
              }
          }
          if (charCode > 31 && (charCode < 48 || charCode > 57)) {
              return false;
          }
          return true;
      }
      

      jsfiddle.net

      【讨论】:

        【解决方案9】:

        使用 JQuery。

        $(document).ready(function()
             {
                //Only number and one dot
                function onlyDecimal(element, decimals)
                {
                    $(element).keypress(function(event)
                    {
                        num = $(this).val() ;
                        num = isNaN(num) || num === '' || num === null ? 0.00 : num ;
                        if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57))
                        {
                            event.preventDefault();
        
                        }
                        if($(this).val() == parseFloat(num).toFixed(decimals))
                        {
                            event.preventDefault();
                        }
                    });
                }
        
                 onlyDecimal("#TextBox1", 3) ;
        
        
        
            });
        

        【讨论】:

        • 迄今为止最好的解决方案 - 如果输入不正确,可能会发出哔哔声?
        • 但是如果第一个符号是点(如果是,我可以在函数中输入更多的小数位数),为什么如果我在点后输入 3 位数字,我不能编辑输入的小数呢?
        【解决方案10】:

        使用 jQuery 并允许负浮点数:

        // Force floats in '.js_floats_only' inputs
        $(document).ready(function() {
            $('.js_floats_only').each(function() {
                // Store starting value in data-value attribute.
                $(this).data('value', this.value);
            });
        });
        
        $(document).on('keyup', '.js_floats_only', function() {
            var val = this.value;
            if ( val == '-' ) {
                // Allow starting with '-' symbol.
                return;
            } else {
                if ( isNaN(val) ) {
                    // If value is not a number put back previous valid value.
                    this.value = $(this).data('value');
                } else {
                    // Value is valid, store it inside data-value attribute.
                    $(this).data('value', val);
                }
            }
        });
        

        【讨论】:

          【解决方案11】:
          $('.number').keypress(function(event){
                      if($.browser.mozilla == true){
                            if (event.which == 8 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 9 || event.keyCode == 16 || event.keyCode == 46){
                                  return true;
                            }
                      }
                      if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
                          event.preventDefault();
                        }
                          });
          

          这适用于所有浏览器。

          【讨论】:

            【解决方案12】:
            <input type="text" data-textboxtype="numeric" />
            <script>
                $(document).on('keydown', '[data-textboxtype="numeric"]', function (e) {
                    // Allow: backspace, delete, tab, escape, enter and . and -
                    if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190, 109, 189]) !== -1 ||
                        // Allow: Ctrl+A
                        (e.keyCode == 65 && e.ctrlKey === true) ||
                        // Allow: home, end, left, right, down, up
                        (e.keyCode >= 35 && e.keyCode <= 40)) {
                        // let it happen, don't do anything
                        return true;
                    }
                    // Ensure that it is a number and stop the keypress
                    if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                        e.preventDefault();
                        return false;
                    }
                    return true;
                });
            </script>
            

            【讨论】:

              【解决方案13】:

              下面的代码我只允许数字和点符号。
              ASCII字符数以47开头,以58结尾,点值为190。

                 $("#Experince").keyup(function (event) {
                      debugger
              
                      if ((event.which > 47
                          && event.which < 58) ||event.which== 190) {
                           if ($("#Experince").val().length > 3) {
              
                      }
                      } // prevent if not number/dot
                      else {
                           $("#Experince").val($("#Experince").val().slice(0, -1))
                      }
              
                  });
              

              【讨论】:

                【解决方案14】:

                对于简单的情况,无需硬编码,一些 html 指令就足够了

                <input type="number" step="0.01"/>
                

                【讨论】:

                  猜你喜欢
                  • 2015-11-26
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多