I need a field where a maximum of 4 numbers can be entered and, if the user enters less than 4 digits, the 4 digits are filled with leading zeros, and do not accept values such as 0, 00, 000, or 0000 .
I made the code below by setting a 4-digit mask with input mask
and doing the correct checks to remove the entered value if it is one of the values quoted above (0, 00, 000 or 0000) or complete with zeros if it is but I could not identify the reason why it is clearing the value typed when you focus the field after typing a valid value, instead of completing with leading zeros or keeping the value typed.
jQuery(function($){
$("#numero").mask("9999");
$("#numero").bind("change focusout", function (){
var num = $(this).val();
if (num == 0 | num == 00 | num == 000 || num == 0000){
$(this).val('');
}
else{
while (num.size < 4){
num = 0 + num;
$(this).val(num);
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scripttype="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery.maskedinput/1.4.1/jquery.maskedinput.min.js"></script>Número<inputtype="text" id="numero" name="numero" maxlength="4"/>