Small Javascript code to complete typed input field

multisites
multisites used Ask the Experts™
on
Imagine I have a form input field like this:

<input type=text name="Cic" size=14>

All I want is a very simple Javascript On event code I could put on this input field so that, if one types a field smaller than 19 characters in size it could complete it with left zeros before sending to the Script called by the Form.

Ex: 4565349560 turns to 00004565349560, 123456 turns to 00000000123456, and so on.

Thanks.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
right this in onSubmit function

var num = 1234;
var str = "" + num;
var len = str.length()

while (len < 15)
{
    str = "0" + str;
}

Commented:
... missed to calculate len again, and use 19 for your case.

while (len < 19)
{
    str = "0" + str;
    len = str.length;
}
Try this:
<script type="text/javascript">
function checkForm() {
  var cic = document.getElementById('Cic');
  while (cic.value.length < 19) {
    cic.value = '0' + cic.value;
  }
}
</script>
<form onsubmit="checkForm()">
<input type="text" id="Cic" name="Cic" size="19">
</form>

Open in new window

Success in ‘20 With a Profitable Pricing Strategy

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

instead of the while loop, I prefer something like that :


cic = "00000000000000".substring(cic.length)+cic;

Open in new window

Author

Commented:
Great, both worked! Just a question: the conversion is being done even when the field is blank. Which piece of code should I add so that the Javascript function worked only when the field is not null (it is not a required field) ?

if(cic!=null && cic.length!="")
   cic = "00000000000000".substring(cic.length)+cic;

Open in new window

I made several mistakes (for me it was 14 instead of 19 and i forget .value)


function checkForm() {
  var cic = document.getElementById('Cic');
  if(cic.value != null && cic.value != "")
   cic.value = "0000000000000000000".substring(cic.value.length)+cic.value;
}

Open in new window

Author

Commented:
Hi, laurent,
That's great, thanks a lot, it worked.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial