简体   繁体   中英

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. 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.

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

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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