【问题标题】:Restricting 3 figures after the decimal places is not working when copy paste value into the input field将粘贴值复制到输入字段时,限制小数点后 3 位无效
【发布时间】:2020-02-18 13:46:57
【问题描述】:

我成功地限制了小数点后的 3 位数字,但是当我将一些随机小数位复制粘贴到文本字段中时,修复不起作用。

$('.min-val').on('keyup', function(e) {
  $(this).val($(this).val().replace(/[^\d.]/g, ''));
  if ($(this).val().indexOf(".") > -1 && ($(this).val().split('.')[1].length > 3)) {
    $(this).val($(this).val().substring(0, $(this).val().length - 1));
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" placeholder="min val" class="min-val" />

即使我复制粘贴数据,如何将小数位数限制为 3?

【问题讨论】:

  • 这是因为您只使用了keyup 事件。试试on('input paste', function(e) {...
  • @Roy 感谢您的回答。我尝试使用 on('input paste', function(e) {... 但它没有帮助..

标签: jquery html jquery-validate


【解决方案1】:

您可以使用正则表达式本身来实现这一点。不过我不擅长。
所以下面的解决方法。 您可以确定要修剪的字符数并使用该数字
var charsToTrim = $(this).val().split('.')[1].length - 3;

$('.min-val').on('keyup', function(e) {
  $(this).val($(this).val().replace(/[^\d.]/g, ''));
  if ($(this).val().indexOf(".") > -1 && ($(this).val().split('.')[1].length > 3)) {
    var charsToTrim = $(this).val().split('.')[1].length - 3;
    $(this).val($(this).val().substring(0, $(this).val().length - charsToTrim));
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" placeholder="min val" class="min-val" />

【讨论】:

    猜你喜欢
    • 2023-04-02
    • 2013-08-21
    • 1970-01-01
    • 2021-11-25
    • 2014-08-31
    • 2012-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多