Link to home
Start Free TrialLog in
Avatar of multisites
multisites

asked on

Small Javascript code to complete typed input field

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.
Avatar of dhiraj05
dhiraj05

right this in onSubmit function

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

while (len < 15)
{
    str = "0" + str;
}
... missed to calculate len again, and use 19 for your case.

while (len < 19)
{
    str = "0" + str;
    len = str.length;
}
Avatar of coolersport
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

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


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

Open in new window

Avatar of multisites

ASKER

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

ASKER CERTIFIED SOLUTION
Avatar of laurent_roy
laurent_roy

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi, laurent,
That's great, thanks a lot, it worked.