-1
<form>
<input type="text" maxlength="5" />
</form>

I need help adding a zero to the text box value if the input has fewer digits than the maximum length of the field. for example: if some one enters 1234 then it should add a zero to it and make it 01234. Same way if someone enters 12 then it should make it 00012 when the user moves out of the text field. We also need to make sure that if user enters 00000 this should not be accepted as input.

Thanks!

3 Answers3

0

This could be what you are looking for:

<!doctype html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
</head>

<body>

  <form>
    <input id="input" style="border:1px solid red" type="text" maxlength="5" onblur="while(this.value.length<parseInt(this.getAttribute('maxlength')))this.value='0'+this.value;" />
  </form>

</body>

</html>
Sebastian Speitel
  • 7,166
  • 2
  • 19
  • 38
0

Use slice of Array.prototype something like below.

function myFunction(){
  s='00000'+document.getElementById("1").value;
  document.getElementById("1").value=s.slice(-5);
}
<input id="1" style="border:1px solid red" type="text" maxlength="5" onfocusout="myFunction()"/>
yajiv
  • 2,901
  • 2
  • 15
  • 25
0

You could use this funny trick :

(new Array(3 + 1)).join("0") // "000"

input = document.getElementById("input");

input.addEventListener("blur", function () {
  var n = this.value.length;
  var max = parseInt(this.getAttribute("maxlength"), 10);
  if (n < max) {
    var l = max - n + 1;
    var prefix = new Array(l).join("0");
    this.value = prefix + this.value;
  }
});
<input id="input" type="text" maxlength="5">