2
I need a field where 4 numbers can be entered at most, and if the user enters less than 4 digits, the 4 digits are completed with zeros on the front, and does not accept values such as 0, 00, 000 or 0000.
I made the code below by setting a 4 digit mask with the input mask
and making appropriate checks to remove the entered value if it is one of the above values (0, 00, 000 or 0000) or complete with zeros if valid, however I could not identify why it is cleaning the entered value by taking the focus of the field after typing a valid value, instead of completing with zeros to the left or keeping the entered value.
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>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery.maskedinput/1.4.1/jquery.maskedinput.min.js"></script>
Número <input type="text" id="numero" name="numero" maxlength="4"/>
It is, but making only this change is not cleaning the
input
by inserting only 0, 00, 000 or 0000 and focusing the field, and not completing the field with the zeros on the left when inserting a valid number.– Leandro
Take a look again.
– thxmxx
Now you are only not completing with zeros on the left by entering a valid value, for example, 21.
– Leandro
I changed it one more time
– thxmxx
Thanks for the help. I had already broken my head enough with this and nothing to work.
– Leandro