简体   繁体   中英

javascript fill input value with 0's till maxlength

i have a input with a maxlength of 13 numbers. Each time you type in a number it gets displayed on the site.

This is working fine but i need a default value of 0 for each of the 13 numbers if the input isn't 13 numbers long.

So if you already typed in 1234 the output should look like this: 1234000000000

simply replace all missing numbers with 0

If the input is completely empty its working with if (input == '') But I always need 13 numbers so I have to fill the input with 0's

 $('#input').keyup(function() { var input = $(this).val(); if (input == '') { input = '0000000000000'; } var i = 0; while (i < 13) { var digit = input.charAt(i); $('.inp' + i + ' > .digit').html(digit); i++; } var fdin = input.charAt(0); // getStructure(fdin); }); 
 div {display: inline-block;} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="input" type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57' maxlength="13"></input> <div class="inp0"><span class="digit">0</span></div> <div class="inp1"><span class="digit">0</span></div> <div class="inp2"><span class="digit">0</span></div> <div class="inp3"><span class="digit">0</span></div> <div class="inp4"><span class="digit">0</span></div> <div class="inp5"><span class="digit">0</span></div> <div class="inp6"><span class="digit">0</span></div> <div class="inp7"><span class="digit">0</span></div> <div class="inp8"><span class="digit">0</span></div> <div class="inp9"><span class="digit">0</span></div> <div class="inp10"><span class="digit">0</span></div> <div class="inp11"><span class="digit">0</span></div> <div class="inp12"><span class="digit">0</span></div> 

edit: made this with it

You can try this approach:

 var number = 123; for(var i = number.toString().length; i<13; i++) { number += '0'; } console.log(number); 

Also:

 var number = 123; number += '0'.repeat(13 - number.toString().length); console.log(number); 

You can use ES8 String.prototype.padEnd()

The padEnd() method pads the current string with a given string (repeated, if needed) so that the resulting string reaches a given length. The padding is applied from the end (right) of the current string.

 var str = "123"; var newStr = str.padEnd(13, "0"); console.log(newStr); 

You can use substr technique by using the below code.

function myFunction(number){
    var newValue = parseInt((number+"0000000000000").substr(0,13));
    return newValue;
}

Hope it helps.

This could also be a possible approach when ES2017's String.padEnd is not available:

var maxLen = 13;
var myNumber = 1234;
var filledNumber = (myNumber + Array(maxLen).fill(0).join('')).substr(0, maxLen);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM