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.
<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.
... missed to calculate len again, and use 19 for your case.
while (len < 19)
{
str = "0" + str;
len = str.length;
}
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>
instead of the while loop, I prefer something like that :
cic = "00000000000000".substring(cic.length)+cic;
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;
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Hi, laurent,
That's great, thanks a lot, it worked.
That's great, thanks a lot, it worked.
var num = 1234;
var str = "" + num;
var len = str.length()
while (len < 15)
{
str = "0" + str;
}