Javascript function that completes the field with zeros on the left

Asked

Viewed 24,995 times

3

I have a field that accepts 4 digits, I would like that, after filling the field, when switching to another field, if the 4 digits are not typed, that the field is auto completed with zeros on the left.

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;  

txtAgencia

2 answers

13


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 it work in an input text, using jquery:

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

3

You can create a function called leftPad, to fill in the values to the left of the value past, using the totalWidth to delimit to how much to fill and using the paddingChar to tell which character is used. I put by default the paddingChar as 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

Browser other questions tagged

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