JavaScript function that completes the field with leading zeros [duplicate]

1

I have a field that accepts 4 digits, I would like, after completing the field, when changing to another field, if the 4 digits are not entered, the field is auto-completed with leading zeros.

What would a JavaScript function look like? And how to call it inside the TextBox below?

Field:

<telerik:RadTextBox ID="txtAgencia" runat="server" Width="80px" MaxLength="4" NumberFormat-DecimalDigits="0" onblur="caractNaoPermit(this, 'numeric'); formatCamp(this,'numeric');" onkeypress="return(validaConteudo(event, this, 'numeric'))" onfocus="removeCaracs(this,'numeric')" />&nbsp;  

    
asked by anonymous 06.01.2017 / 12:51

2 answers

3

A simple single line solution:

("0000" + n).slice(-4)

where n is your number:

("0000" + 1).slice(-4); // "0001"
("0000" + 12).slice(-4); // "0012"
("0000" + 123).slice(-4); // "0123"
("0000" + 1234).slice(-4); // "1234"

To make an input text work, using jquery:

<input id="campo_01" type="text">
<script>
    $("#campo_01").keyup(function() {
        this.value = ("0000" + this.value).slice(-4)
    });
</script>
    
06.01.2017 / 13:00
1

You can create a function called leftPad , to fill in the values to the left of the value passed, using totalWidth to delimit up to how much to fill and using paddingChar to say which character is used . I have set paddingChar to 0 .

function leftPad(value, totalWidth, paddingChar) {
  var length = totalWidth - value.toString().length + 1;
  return Array(length).join(paddingChar || '0') + value;
};

leftPad(1, 4); // 0001
leftPad(12, 4); // 0012
leftPad(123, 4); // 0123
leftPad(1234, 4); // 1234
leftPad(12345, 4); // 12345
    
06.01.2017 / 12:57