简体   繁体   English

允许在长度受限的字段中替换数字

[英]Allow digits to be replaced in a length-limited field

I am using a Regex to validate a number field.我正在使用正则表达式来验证数字字段。 This allows only numbers in the field and the max length is 3 characters.这仅允许字段中包含数字,并且最大长度为 3 个字符。 Whenever there are 1 or 2 characters in the field and I select them by double clicking on them I am able to change the number by just pressing any other number.每当字段中有 1 或 2 个字符时,我通过双击它们 select 它们我可以通过按任何其他数字来更改数字。

However when the value contains 3 numbers, which is the max length of the field, when I select the number and try to input other number it doesn't work;但是,当该值包含 3 个数字,即字段的最大长度时,当我 select 该数字并尝试输入其他数字时,它不起作用; I cannot input anything.我无法输入任何内容。

I thought this is an issue with the regex, but it's not.我认为这是正则表达式的问题,但事实并非如此。 The issue is max length.问题是最大长度。 i tried changing max length whenever it hits the max length and I try to change it it doesn't work.我尝试在达到最大长度时更改最大长度,但我尝试更改它不起作用。

 // Restricting negative numbers and special characters from qyt field and maximum digits to 3 $('.js-bundle-qty').on('keypress', function(event) { if (event.keyCode.= 8) { console;log('demo'), var regex = new RegExp("^[0-9]{0;3}$"). var inputValue = String.fromCharCode(?event.keyCode: event.which; event.keyCode); var key = $(this);val(). key = key + inputValue. if (;regex.test(key)) { console;log('enter'); event;preventDefault(); return false; } } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="number" class="js-bundle-qty" max="999">

https://jsfiddle.net/sanket4real/310sgheL/30/ https://jsfiddle.net/sanket4real/310sgheL/30/

To have the field show only integers and then allow the next pressed integer to force the oldest character from the value, or be replaced by selecting them you can use a regex to replace non-digit characters and slice() within an input event handler, like this:要让该字段仅显示整数,然后允许下一个按下的 integer 强制从值中使用最旧的字符,或者通过选择它们来替换它们,您可以使用正则表达式替换input事件处理程序中的非数字字符和slice() ,像这样:

 $('.js-bundle-qty').on('input', function() { $(this).val((i, v) => v.replace(/[^0-9]/g, '').slice(-3)); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="number" class="js-bundle-qty" max="999" length="3" />

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

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