5
I have a numerical type input, which should only receive numbers (obvious).
However, some browsers let the user type alphanumeric.
However, this is not the only problem.
I need 0 to be displayed on the left as long as the input value has not reached the 4 character limit disregarding the zeros on the left.
For example: the initial value of the field is 0000 and the uzuário digita 1, so the input must have the value 0001.
I tried with Jquery Mask, but it just limits the type of data and the amount of characters, but does not format zeros on the left.
$(document).ready(function () {
//$('#client-number').mask('0000', {placeholder: '0000'});
/*Esse foi o melhor script que consegui fazer, porem ele não permite backspace, delete nem arrows, o que torna a experiência ruim*/
$('#client-number').keydown(function (evt) {
var fieldVal = $(this).val();
var key = evt.keyCode;
var char = String.fromCharCode((96 <= key && key <= 105)? key-48 : key);
if (!isNaN(char)) {
fieldVal = $(this).val() + char;
}
if (fieldVal < 9999 && evt.which != 32) {
$(this).val(paddy(fieldVal, 4));
return false;
} else {
return false;
}
});
function paddy(n, p, c) {
var pad_char = typeof c !== 'undefined' ? c : '0';
var pad = new Array(1 + p).join(pad_char);
return (pad + n).slice(-pad.length);
}
});
<script src="https://github.com/igorescobar/jQuery-Mask-Plugin/blob/master/dist/jquery.mask.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="client-number" class="form-control" autofocus pattern="[0-9]*" inputmode="numeric" min="0" max="9999"
name="number" />
Here’s an example: http://jsfiddle.net/donmccurdy/3sQrm/ You can also create a Jsfiddle with your code, this stimulates better answers in my view
– Not The Real Hemingway
Have you seen that question?
– Renan Gomes
I’ve seen @Renan, I can put the zero on the left. There are a thousand ways to do this, but I can’t put the 0 and still limit it to 4 characters at the same time. I’ll put up some examples of code I’ve tried
– Riva Junior
I limited the characters and put to format when typing... missing something?
– Allan Andrade