Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

Q1798 How can I automatically format a date like 1/5/01 while it is being typed in by the user?

You are here: irt.org | FAQ | JavaScript | Form | 3.5 | Q1798 [ previous next ]

The onblur handles the millenium AND Netscape. A side effect of the keyCode test in IE is the user can only type digits and the slash

Script tested in NS4.7 and IE5.5 on window98

<form>
<input type="text" name="test" value=""
onKeyUp="
if (!document.all) return;
key = window.event.keyCode;
val = this.value;
if (key!=16 && key !=8 && (key<48 || key>57)) {
 val=val.substring(0,val.length-1);
 return;
}
if (val.indexOf('/') == 1)
   val = '0'+val;
if (val.length>3 && val.indexOf('/',3) == 4)
   val = ''+val.substring(0,3)+'0'+val.substring(3);
this.value=val"
onBlur="
if (this.value && this.value.length>5) {
   parts = this.value.split('/');
   if (parts.length!=3) return;
   if (parts[0].length == 1) parts[0]='0'+parts[0];
   if (parts[1].length == 1) parts[1]='0'+parts[1];
   if (parts[2].length ==2)  parts[2]='20'+parts[2];
   this.value=parts.join('/');
}
">
</form>

Submitted by Michel Plungjan

©2018 Martin Webb