JQuery 只允许小数点后两个数字

IT技术 javascript jquery keycode
2021-03-01 17:23:34

我在这里找到了以下 JQuery 函数它可以防止用户输入任何不是数字或单个小数的内容。该功能运行良好,但我想对其进行改进,以防止用户输入 3 个或更多小数位,即禁止 99.999 并允许 99.99。有任何想法吗?

 function checkForInvalidCharacters(event, inputBox){                            
     if ((event.which != 46 || inputBox.val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {          
                event.preventDefault();           
            }   
     };
6个回答

逻辑是每次用户输入数字时,您都必须检查两件事。

  1. 用户是否输入了小数点?
  2. 小数点是否超过两位?

对于第一个您可以使用$(this).val().indexOf('.') != -1

对于第二个您可以使用$(this).val().substring($(this).val().indexOf('.'), $(this).val().indexOf('.').length).length > 2

EDIT-1
此外,您必须添加event.which != 0 && event.which != 8以便箭头键和退格键在 Firefox 中工作(Manoj 评论)

EDIT-2
另外,$(this)[0].selectionStart >= text.length - 2如果光标位于小数点左侧,则必须添加以便添加数字(BIdesi 注释)

EDIT-3
此外,您必须检查用户是否已删除.并将其放置在其他地方,从而创建一个小数点后超过 2 位的值。所以你必须添加 $this.val($this.val().substring(0, $this.val().indexOf('.') + 3));以减少额外的数字(Gilberto Sánchez 评论)

EDIT-4
要处理粘贴的数据,您必须绑定一个粘贴事件处理程序。然后您必须检查粘贴的数据是否.text.indexOf('.') > -1 和 小数点后超过 2 位的数字text.substring(text.indexOf('.')).length > 3如果是这样,您必须削减额外的数字。您还必须检查用户是否使用$.isNumeric()(darasd 评论)输入了数字输入

这是代码:

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

    var text = $(this).val();
    if ((event.which == 46) && (text.indexOf('.') == -1)) {
        setTimeout(function() {
            if ($this.val().substring($this.val().indexOf('.')).length > 3) {
                $this.val($this.val().substring(0, $this.val().indexOf('.') + 3));
            }
        }, 1);
    }

    if ((text.indexOf('.') != -1) &&
        (text.substring(text.indexOf('.')).length > 2) &&
        (event.which != 0 && event.which != 8) &&
        ($(this)[0].selectionStart >= text.length - 2)) {
            event.preventDefault();
    }      
});

$('.number').bind("paste", function(e) {
var text = e.originalEvent.clipboardData.getData('Text');
if ($.isNumeric(text)) {
    if ((text.substring(text.indexOf('.')).length > 3) && (text.indexOf('.') > -1)) {
        e.preventDefault();
        $(this).val(text.substring(0, text.indexOf('.') + 3));
   }
}
else {
        e.preventDefault();
     }
});
.number {
  padding: 5px 10px;
  font-size: 16px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="number" />

@BIdesi 好收获!我更新了代码,现在您的场景可以正常工作了。
2021-05-02 17:23:34
@Manoj 你能指出我看到的确切问题吗?你想输入什么但没有按预期工作?
2021-05-03 17:23:34
不适用于场景,输入 12.34 然后使用箭头键来到'2'的位置并删除它并用其他数字替换它,你不能
2021-05-09 17:23:34
谢谢,但是如果我删除了.然后我把它放在另一个地方会发生什么?例如,如果我有 22.45,那么我去掉小数点并把它写成这样:2.245?
2021-05-10 17:23:34
@Manoj 我注意到在 Firefox 中退格不起作用。所以我更新了我的答案。谢谢指出
2021-05-13 17:23:34

也可以用正则表达式来完成:

    $('.class').on('input', function () {
        this.value = this.value.match(/^\d+\.?\d{0,2}/);
    });

将 css 选择器.class命名为您喜欢的任何名称并将其放在输入中。

如果我们在数字之前只写十进制,那么它确实会删除输入的值。它不应删除输入的值,但不允许在第一个位置输入小数 (.)。
2021-05-18 17:23:34

我已经更新了一些额外情况的功能。

  1. 它将允许负数
  2. 当右边已经有 2 位数字时,它将允许您编辑小数点的左边
  3. 它允许您在 Firefox 中使用箭头键和退格键
  4. 它还处理粘贴的数据

/**
 * Given an input field, this function will only allow numbers with up to two decimal places to be input.
 * @param {object} element
 * @return {number}
 */
function forceNumber(element) {
  element
    .data("oldValue", '')
    .bind("paste", function(e) {
      var validNumber = /^[-]?\d+(\.\d{1,2})?$/;
      element.data('oldValue', element.val())
      setTimeout(function() {
        if (!validNumber.test(element.val()))
          element.val(element.data('oldValue'));
      }, 0);
    });
  element
    .keypress(function(event) {
      var text = $(this).val();
      if ((event.which != 46 || text.indexOf('.') != -1) && //if the keypress is not a . or there is already a decimal point
        ((event.which < 48 || event.which > 57) && //and you try to enter something that isn't a number
          (event.which != 45 || (element[0].selectionStart != 0 || text.indexOf('-') != -1)) && //and the keypress is not a -, or the cursor is not at the beginning, or there is already a -
          (event.which != 0 && event.which != 8))) { //and the keypress is not a backspace or arrow key (in FF)
        event.preventDefault(); //cancel the keypress
      }

      if ((text.indexOf('.') != -1) && (text.substring(text.indexOf('.')).length > 2) && //if there is a decimal point, and there are more than two digits after the decimal point
        ((element[0].selectionStart - element[0].selectionEnd) == 0) && //and no part of the input is selected
        (element[0].selectionStart >= element.val().length - 2) && //and the cursor is to the right of the decimal point
        (event.which != 45 || (element[0].selectionStart != 0 || text.indexOf('-') != -1)) && //and the keypress is not a -, or the cursor is not at the beginning, or there is already a -
        (event.which != 0 && event.which != 8)) { //and the keypress is not a backspace or arrow key (in FF)
        event.preventDefault(); //cancel the keypress
      }
    });
}

forceNumber($("#myInput"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="myInput" />

谢谢!我添加了删除数字和“。”的可能性。一次输入:

event.keyCode !== 8执行该操作backspace

event.keyCode !== 46执行该操作delete

$( document ).ready(function() {

    $('#Ds_Merchant_Amount').keypress(function(event) {
    if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57) ) {
        if (event.keyCode !== 8 && event.keyCode !== 46 ){ //exception
            event.preventDefault();
        }
    }
    if(($(this).val().indexOf('.') != -1) && ($(this).val().substring($(this).val().indexOf('.'),$(this).val().indexOf('.').length).length>2 )){
        if (event.keyCode !== 8 && event.keyCode !== 46 ){ //exception
            event.preventDefault();
        }
    }
  });
});

带有小数点的数字值最多 2 个小数点验证。依赖jQuery

HTML -

<span>Float</span>
<input type="text" name="numeric" class='allownumericwithdecimal'>
<div>Numeric values only allowed  (With Decimal Point) </div>

JQuery 代码 -

方法1-

    $(".allownumericwithdecimal").on("keypress keyup blur", function (event) {
     var patt = new RegExp(/[0-9]*[.]{1}[0-9]{2}/i);
     var matchedString = $(this).val().match(patt);
     if (matchedString) {
         $(this).val(matchedString);
     }
     if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
         event.preventDefault();
     }
 });

方法 2 -

 $(".allownumericwithdecimal").on("keypress keyup blur", function (event) {
     var patt = new RegExp(/(?<=\.\d\d).+/i);
     $(this).val($(this).val().replace(patt, ''));

     if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
         event.preventDefault();
     }
 });
我在一个项目中实现了方法 2,但发现它只在 Chrome 中有效。正向后视在其他浏览器中不起作用(我在几个小时后了解到)。方法 1 适用于我测试的所有四种浏览器,尽管我使用了: var patt = new RegExp(/^\d+\.\d\d/i);
2021-05-19 17:23:34