Input mask with zeros on the left

Asked

Viewed 4,468 times

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

  • 1

    Have you seen that question?

  • 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

  • I limited the characters and put to format when typing... missing something?

2 answers

6


You can use the jQuery.maskMoney with some changes in the settings of input for type="text" and maxlength="4", and in the maskMoney: precision:3 and decimal:'' :

Sample code:

$(function() {
  $("#tnumber").maskMoney({
    precision: 3,
    decimal: ''
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-maskmoney/3.0.2/jquery.maskMoney.min.js">
</script>

<input type="text" id="tnumber" maxlength="4" pattern="[0-9]*">


Another solution is to use jquery.maskedinput with the following settings:

$("#tnumber").mask("9999", { placeholder: "0", autoclear: false });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.maskedinput/1.4.1/jquery.maskedinput.min.js"></script>
<input type="text" id="tnumber" maxlength="4" pattern="[0-9]*">

Observing: there is nothing ready on the subject, I did a scan on the internet, and I did not find anything better than this, but, I will give one more searched

References:

  • Almost works. This code has a bug. Try to put a digit before all zeros, it continues there, even exceeding the limit that is 4 digits

  • @Rivajunior, I made another example with jquery.maskedinput this can be a viable solution through a behavior not seen in the other plugin, the funniest that the html accepted the typing of 5 numbers inflicted on the imposed rules of maxlength, the second I believe is better for what you need.

  • 1

    was great his second example, I just noticed a problem in firefox. It does not let the user navigate the arrow keys on the keyboard.

  • 1

    @Rivajunior looks, we are, seeing there to make a package for this in a javascript group, for now the second example is the best apparent solution, when something comes out I put and warn you . About browsers, it’s our big problem, they don’t do everything as they should.

5

Without using external libs, besides the jQuery you already use, I did the example below with the requested formatting.

UPDATE 01: I CHANGED IT TO THE EVENT keyup

UPDATE 02: LIMITATION OF 4 CHARACTERS

UPDATE 03: SELECT ALL UPON RECEIVING FOCUS

UPDATE 04: Running on various browsers

$('#client-number').keyup(function(){
    var valor_bruto = $('#client-number').val().replace(/[^\d]/g, '');
    var valor = parseInt(0 + valor_bruto);
    var novoValor = pad(valor, 4);
    $('#client-number').val(novoValor);
});


$(document).ready(function() {
    $('#client-number').focus(function() { $(this).select(); } );
});

function pad (str, max) {
  str = str.toString();
  str = str.length < max ? pad("0" + str, max) : str; // zero à esquerda
  str = str.length > max ? str.substr(0,max) : str; // máximo de caracteres
  return str;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<input type="text" id="client-number" class="form-control" autofocus name="number" value="0000" />

  • @Virgilionovic, code updated and running in firefox. Thanks for the remark!

  • Ok removed comment

  • @Allanandrade liked the idea of selecting everything upon receiving focus. The implementation is working, but not only in firefox it is possible to navigate the input using the arrow keys. And when a number is deleted at the beginning, for example, the cursor goes back to the end of the input, I found it a little annoying. Plus, your code is great!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.