Home > Mobile >  HTML Input Type Number with Leading Zero on Input
HTML Input Type Number with Leading Zero on Input

Time:07-05

I have HTML Input Type=Number with maxlength='6' and I want it to have leading zeros while typing certain numbers. Leading zeros automatically adjusts depending on your number input.

Example: While typing '12' in the field, it should add leading zeros making it '000012' instead, or typing '123', it should be '000123', and so on.

How can I achieve this using JS/JQuery?

Thank you for helping.

CodePudding user response:

something like this:

function addLeadingZero(event) {
    // get maxlength attr
    const maxLength = parseInt(event.target.getAttribute("maxlength"))
    // "0".repeat(maxLength) <-- create default pad with maxlength given
    // append zero and slice last of attr maxlength value
    const newValue = ("0".repeat(maxLength)   event.target.value.toString()).slice(-maxLength);
    // change the value of input
    event.target.value = newValue
}
<!-- @event onkeyup to make sure function run on every key up -->
<!-- @event onchange to make sure function run when we click on arrow up/down -->
<input type="number" maxlength="6" onkeyup="addLeadingZero(event)" onchange="addLeadingZero(event)">

To support negative value :

function addLeadingZero(event) {
    // get maxlength attr
    const maxLength = parseInt(event.target.getAttribute("maxlength"))
    // check and flag if negative
    const isNegative = parseInt(event.target.value) < 0
    // "0".repeat(maxLength) <-- create default pad with maxlength given
    // Math.abs(event.target.value) to make sure we proceed with positive value
    // append zero and slice last of attr maxlength value
    let newValue = ("0".repeat(maxLength)   Math.abs(event.target.value).toString()).slice(-maxLength);
    // add - if flag negative is true
    if (isNegative) {
      newValue = "-" newValue
    }
    // change the value of input
    event.target.value = newValue
}
<!-- @event onkeyup to make sure function run on every key up -->
<!-- @event onchange to make sure function run when we click on arrow up/down -->
<input type="number" maxlength="6" onkeyup="addLeadingZero(event)" onchange="addLeadingZero(event)">

  • Related