【问题标题】:How can I create an input field that allows only numbers and comma and dot?如何创建一个只允许数字和逗号和点的输入字段?
【发布时间】:2019-10-11 11:23:57
【问题描述】:

我正在使用 select2。所以它不是一个实数输入字段我尝试创建一个只允许带小数的数字的输入字段:

<input type="text" name="numeric" class='select2 allownumericwithdecimal'> 

 $(".allownumericwithdecimal").on("keypress keyup blur",function (event) {
        $(this).val($(this).val().replace(/[^0-9\.]/g,''));
        if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
          event.preventDefault();
        }
      });

我现在需要的是,它不仅允许点,还应该允许逗号。这是我的方法:

 $(".allownumericwithdecimal").on("keypress keyup blur",function (event) {
        $(this).val($(this).val().replace(/[^0-9\.]/g,''));
        if ((event.which != 46 || $(this).val().indexOf('.') != -1 || $(this).val().indexOf(',') != -1) && (event.which < 48 || event.which > 57)) {
          event.preventDefault();
        }

仍然不允许逗号.. });

【问题讨论】:

  • 使用type="number" 并让浏览器决定如何为给定的位置/文化正确格式化数字。
  • Documentation of &lt;input type="number"&gt;
  • 不,我不能。因为我使用的是select2。所以它不是一个真正的输入字段
  • 还有类型号我仍然可以在字段内写字母
  • 不过是jquery函数的问题

标签: jquery function input jquery-select2


【解决方案1】:

我已经修复了你的代码

 $(".allownumericwithdecimal").on("keypress keyup blur",function (event) {
        $(this).val($(this).val().replace(/[^0-9\.|\,]/g,''));
        debugger;
        if(event.which == 44)
        {
        return true;
        }
        if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57  )) {
        
          event.preventDefault();
        }
      });
        
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="numeric" class='select2 allownumericwithdecimal'>

【讨论】:

  • 谢谢,我才意识到我可以写“。”只能写一次,但是“,”我可以写多次
【解决方案2】:
$(".allownumericwithdecimal").on("keypress keyup blur",function (event) {
        $(this).val($(this).val().replace(/[^0-9\.]/g,''));
        if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57 || event.whitch === 188 || event.which === 110)) {
          event.preventDefault();
        }

更多信息:https://keycode.info/

【讨论】:

  • 我试过你的代码。我也试过这个,但不幸的是我仍然只能按“。”不是“,”
  • 我已经检查了您的代码,我认为您应该检查一次此代码是否有效。?
【解决方案3】:

您不应该监听键盘事件 (keydown / keypress / keyup) 这样做,因为输入的值也可以通过粘贴或拖放文本来更新,您有很多例外情况不应该阻止,如箭头、删除、转义、全选、复制、粘贴等快捷方式...

相反,只需监听 input 事件,解析其值以提取其中的所有数字,然后更新其值以仅保留这些数字和一个十进制指示符。

基本示例如下所示:

const input = document.getElementById('input');

input.oninput = () => {
  const matches = input.value.match(/[\d.,]/g);

  if (!matches) return;

  let hasDecimalSeparator = false;

  input.value = matches.filter((d) => {
    const isDecimalSeparator = d === '.' || d === ',';

    if (!isDecimalSeparator) return true;

    if (hasDecimalSeparator) {
      // We already have one decimal separator, so ignore this one:
      return false;
    }

    // Remember we have just found our first decimal separator:
    hasDecimalSeparator = true;

    // But keep this one:
    return true;
  }).join('');
};
&lt;input id="input" type="text" /&gt;

这可以完成工作,并且可以很好地粘贴和拖放,但您会注意到它有两个问题:

  • 当您输入不应该输入的字符时,光标会移动。

  • 如果您尝试编写第二个十进制指标,如果新指标在前一个指标的左侧,它将更新值;如果它在右边,它会保留旧的。

让我们解决这些问题:

const input = document.getElementById('input');

let decimalSeparatorPosition = null;

input.onkeydown = ({ key }) => {
  decimalSeparatorPosition = key === '.' || key === ',' ? input.selectionStart : null;
};

input.oninput = (e) => {
  const matches = input.value.match(/[\d.,]/g);

  if (!matches) return;
  
  const cursorPosition = input.selectionStart - 1;

  let hasDecimalSeparator = false;

  input.value = matches.filter((d, i) => {
    const isDecimalSeparator = d === '.' || d === ',';

    if (!isDecimalSeparator) return true;

    if (decimalSeparatorPosition !== null && i !== decimalSeparatorPosition) {
      // Ignore any decimal separators that are not the one we have just typed:
      return false;
    }

    if (hasDecimalSeparator) {
      // We already have one decimal separator, so ignore this one:
      return false;
    }

    // Remember we have just found our first decimal separator:
    hasDecimalSeparator = true;

    // But keep this one:
    return true;
  }).join('');
  
  // Keep cursor position:
  input.setSelectionRange(cursorPosition + 1, cursorPosition + 1);
};
&lt;input id="input" type="text" /&gt;

请注意,这仍然存在一些问题:

  • 如果你按下一个被过滤掉的键,比如一个字母,光标仍然会移动一个位置。

  • 如果不是键入小数分隔符,而是粘贴或删除它或包含其中一个或多个的文本,则保留的仍然是最左边的那个,可能不是新的。

但是,这应该为您提供一个很好的起点来实现您所需要的。

另外,请注意 e.whiche.keyCode 已弃用,因此您应该改用 e.keye.code。您可以使用https://keyjs.dev 检查它们的值:

免责声明:我是作者。

【讨论】:

    猜你喜欢
    • 2022-09-22
    • 1970-01-01
    • 2017-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-31
    • 1970-01-01
    相关资源
    最近更新 更多