There is a script that limits the number of introductory characters to 3 and only numbers are allowed.

But the bug is that after I entered 3 characters, I removed the focus from the input, and then once again took the input into focus, then the 3rd character is removed.

How to fix the script so that you can enter ONLY numbers, DO NOT enter the first 0, limit the input to only 3 characters?

$('body').on('click keypress', '.btn-input', function(key) { $this = $(this); $maxLen = 2; if (key.charCode < 48 || key.charCode > 57) return false; if ($this.val().length > $maxLen) $this.val($this.val().substr(0, $maxLen)); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input class="btn-input order-count" type="text" > 

https://jsfiddle.net/4gym7k8h/

  • keypress with keyup , and the string if (key.charCode < 48 || key.charCode > 57) return false; put it at the very end, - Alexey Shimansky
  • Yes it works. But I do not like the fact that the symbols disappear before our eyes, but I wanted them not to be introduced. + I can enter letters, but before this letter was not entered - GilB Ert
  • ok, then after $maxLen = 2; leave it like this: if ($this.val().length > $maxLen) return false; if (key.charCode < 48 || key.charCode > 57) return false; if ($this.val().length > $maxLen) return false; if (key.charCode < 48 || key.charCode > 57) return false; ........... jsfiddle.net/4gym7k8h/1 - Alexey Shimansky
  • In, it works. But how now to make it impossible for 0 to be entered first? - GilB Ert
  • a bit of logic and if ($this.val().length == 0 && key.charCode == 48) return false; - Alexey Shimansky

1 answer 1

 $('body').on('click keypress', '.btn-input', function(key) { $this = $(this); $maxLen = 2; // ограничение по длине if ($this.val().length > $maxLen) return false; // ограничение по вводу нуля в начале if ($this.val().length == 0 && key.charCode == 48) return false; // ограничение по символам if (key.charCode < 48 || key.charCode > 57) return false; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input class="btn-input order-count" type="text" > 

  • It should be noted that this option still allows you to insert arbitrary text of arbitrary length into the field (Ctrl-V). :) - Yaant
  • @Yaant well, depending on the type of browser and the wishes of the workers, everything depends. For example, for some browsers it is generally enough to write the maxlength="3" attribute in the input and not to be soared by the script and not worried about Ctrl-V)) anyway, if the field is designed for a specific number of digits, then the user has no reason to deceive. And if he specifically deceives, then this is a bad uncle and from him, one way or another, the check on the server should be ..... in general, there is a lot to do and screw and spit ...... it all depends .... - Alexey Shimansky