javascripthtmlleading-zero

HTML Input Type Number with Leading Zero on Input


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.


Solution

  • something like this:

    document.querySelector("input[type=number]").addEventListener('input', addLeadingZero)
    
    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">

    To support negative value :

    document.querySelector("input[type=number]").addEventListener('input', addLeadingZero)
    
    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">

    Note : while this answer is correct for more smoother change please check additional answer given by @science fun for using addEventListener.

    edit: applied addEventListener.

    document.querySelector("input[type=number]").addEventListener('input', addLeadingZero)