« More Fun with ImpAmp
Looking for a Name »

Javascript Time Entry Field

For a project I am doing for my dad, I created a form that requires the user to input lots of times. This was to be done in the format "HH:MM:SS". After I created the form and handed the project over for testing, it was mentioned that typing a colon is a pain and it would be nice if it was filled in automatically.

No problem!

So I set the default value of the field to "00:00:00". This did not help, because you need to overwrite the existing information and it became a pain.

Ach well - I'll use javascript

So I thought that this must be a fairly simple task and used quite regularly on the internet in different places so I started looking around for "javascript time data entry" and other searches. Unfortunately this only brought up many javascript calendars to enter dates and javascipt clocks to show an analogue or digital clock on your page.

I DON'T WANT THAT!!!

So instead I hacked myself.

<script type="text/javascript" charset="utf-8">
  document.onkeyup = function keyPress(event){
    field = document.getElementById('time');
    str = field.value.split(":");
    if (str.length 2) && !(str.charAt(2)=='.'){
      indx = field.value.lastIndexOf(':')+3;
      field.value = field.value.slice(0,indx)+"." +
      field.value.slice(indx);
    }
  }
</script>

with this script embedded in the of the document (or an external js file), the field with id "time" would be checked every time a key (or click) has been pressed. If there are 2 characters after the last colon, then a colon is inserted until 3 blocks of characters have been entered. After this if the user keeps typing, a "." is inserted after the first 2 characters after that last colon to allow inputting of sub second accuracy.

Go Top

Comments

To comment on this article, send me an email

No comments yet.