I have an input field
in thymeleaf HTML
with number validation in javascript
, according to my research, there is several ways, how to do it.
One of them:
$(document).ready(function () {
$("#quantity").keypress(function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The question: What is 0 in first if statement?
According to this key code 8 is backspace and numbers between 48 - 57 are numbers (i.e.: 1,2,3,...,9).
In the case of the keypress
event, the value 0 is given for most of the keys that do not produce a character. Exceptions exist, such as backspace. Also, the actual codes are implementation (incl. hardware) dependent.
When e.which
is zero, the code may assume that no printable character is being generated, and so there is no reason to block it. This is useful especially for arrow and soft keys: you'll want to allow the user to move the caret with left and right keys, possibly together with Shift or Ctrl. Nor would you want to block the user from refreshing the page with F5, or deleting a character with Del, or to move to the next input field with Tab. All of those keys come with e.which
equal to 0.
However, the script is not perfect. For instance, it does not allow the user to use clipboard handling shortcuts, such as Ctrl+C.
In general it is not advised to block input keys like that, as you don't want the user to think their keyboard is stuck. Better is to allow the keys to render the corresponding characters, but (only) indicate via visual clues that the input is not valid.