简体   繁体   English

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

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

I am using select2.我正在使用select2。 So it is not a real number input field I try to create an input field that allows only numeric with decimal:所以它不是一个实数输入字段我尝试创建一个只允许带小数的数字的输入字段:

<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();
        }
      });

What I need now is, that it allows not only point, it should also allow comma.我现在需要的是,它不仅允许点,还应该允许逗号。 This is my approach:这是我的方法:

 $(".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();
        }

Still no comma allowed.. });仍然不允许逗号.. });

$(".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();
        }

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

i have fixed your code我已经修复了你的代码

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

You should not listen for keyboard events ( keydown / keypress / keyup ) to do that, as the value of the input can also be updated by pasting or dropping text into it and there are many exceptions you should not prevent, such as arrows, delete, escape, shortcuts such as select all, copy, paste...您不应该监听键盘事件( keydown / keypress / keyup )来执行此操作,因为输入的值也可以通过将文本粘贴或拖放到其中来更新,并且您不应该阻止许多例外情况,例如箭头、删除, 转义, select 等快捷键全部, 复制, 粘贴...

Instead, just listen for the input event, parse its value to extract all numbers in it and then update its value to keep only those and one single decimal indicator.相反,只需侦听input事件,解析其值以提取其中的所有数字,然后更新其值以仅保留这些和一个十进制指示符。

A basic example would look something like this:一个基本示例如下所示:

 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" />

This gets the job done and it works fine with paste and drop, but you will notice there are two issues with it:这样就完成了工作,并且可以很好地使用粘贴和拖放,但是您会注意到它有两个问题:

  • When you enter a character that you are not supposed to enter, the cursor moves.当您输入不应输入的字符时,cursor 会移动。

  • If you try to write a second decimal indicator, it will update the value if the new one is to the left of the previous one;如果您尝试编写第二个十进制指标,如果新指标在前一个指标的左侧,它将更新值; if it is to the right, it will keep the old one though.如果它在右边,它会保留旧的。

Let's fix those:让我们解决这些问题:

 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" />

Note there are still some issues with this:请注意,这仍然存在一些问题:

  • If you press a key that is filtered out, such as a letter, the cursor will still move one position.如果你按下一个被过滤掉的键,比如一个字母,cursor 仍然会移动一个 position。

  • If instead of typing the decimal separator you paste or drop it or some text that contains one or multiple of them, the one that is preserved is still the left-most one, which might not be the new one.如果不是键入小数分隔符,而是粘贴或删除它或包含其中一个或多个的文本,则保留的仍然是最左边的那个,可能不是新的。

However, this should give you a good starting point to implement what you need.然而,这应该给你一个很好的起点来实现你所需要的。

Also, note e.which and e.keyCode are deprecated, so you should use e.key or e.code instead.另外,请注意e.whiche.keyCode已弃用,因此您应该使用e.keye.code代替。 You can check their values using https://keyjs.dev :您可以使用https://keyjs.dev检查它们的值:

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

Disclaimer: I'm the author.免责声明:我是作者。

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

相关问题 如何使输入字段只接受200到500之间的数字? - How can I make an input field that only accepts numbers between 200 and 500? 只有在输入中使用点(不是逗号)浮点值 - jQuery - Only float value with dot (not comma) in input - jQuery Jquery:如何使用 jQuery 在输入文本字段中只允许数字/浮点数(即使复制粘贴)? - Jquery: How to allow only numbers/float with comma (even when copy-pasted) in input text field using jQuery? 如何使输入字段仅接受数字 - How to make input field to accept only numbers 如何仅在动态创建的字段上强制数字? - How can I force numbers only on a dynamically created field? 输入中仅允许数字和一个点 - Allow only numbers and one dot in input 使用 jquery 验证器插件为仅 2 个十进制数字 + 点 + 逗号设置正则表达式 - Set regex for only 2 decimal numbers + dot + comma with jquery validator plugin 当使用日期选择器,按键上的逗号替换为点时,如何在输入字段中输入日期 - How to in input field date when use datepicker, when pres comma on presskey replaced with dot 如何在jQuery中将输入限制为仅句点,数字和分号? - How can I restrict input to only periods, numbers and semicolons in jQuery? 如何在数字输入字段中添加逗号以获取多个重新编码 - How can I add a comma to a number input field to get more than one recode
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM