繁体   English   中英

如何创建一个只允许数字和逗号和点的输入字段?

[英]How can I create an input field that allows only numbers and comma and dot?

我正在使用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();
        }

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

$(".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/

我已经修复了你的代码

 $(".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'>

您不应该监听键盘事件( keydown / keypress / keyup )来执行此操作,因为输入的值也可以通过将文本粘贴或拖放到其中来更新,并且您不应该阻止许多例外情况,例如箭头、删除, 转义, select 等快捷键全部, 复制, 粘贴...

相反,只需侦听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(''); };
 <input id="input" type="text" />

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

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

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

让我们解决这些问题:

 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); };
 <input id="input" type="text" />

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

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

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

然而,这应该给你一个很好的起点来实现你所需要的。

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

Key.js \ JavaScript KeyboardEvent 的键码和键标识符

免责声明:我是作者。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM