View Full Version : How to insert colon automatically after entering hours in hh:mm format

09-30-2011, 11:54 AM

I had a requirement in javascript.If I enter time as 12 it should automatically insert colon after hours and shoud allow user to enter minutes.

First enter hours 12

while we are ready to insert minutes it should automatically insert colon as well as minutes.

function autoTabTimes(input, len) {

if (input.value.length == 2) {
if (input.value.indexOf(":") == -1) {
input.value = input.value + ":";
var str = input.value.split(":");
if (str[0].length == 1) {
input.value = "0" + str[0];

if (input.value.length >= len) {
input.value = input.value.slice(0, len);
input.form[(getIndex(input) + 1)].focus();


return true;

The above code is working but it is not allowing user to edit the time back space is not working.

Philip M
09-30-2011, 01:51 PM
Double posted :( at

If you post in multiple forums you will find that you may not get an answer in any of them. People do not want to waste time answering a question when it has perhaps already been answered elsewhere.
There are few things in forums more irritating than taking the time to unsnarl someone's markup, javascript and css, figure out the fix, and post it only to find you've wasted your time because a duplicate post in another forum has already been answered.

Back space works just fine but your code in effect cancels it.

Try this instead:-

<script type = "text/javascript">

function autoTabTimes(input) {
var len = input.value.length;
if (len<3) {
alert ("Invalid time - re-enter it");
input.value = "";
return false;
if (len==3){
input.value ="0" + input.value;
var final = input.value.split("");
var h = Number(final[0] + final[1]);
var m = Number(final[2] + final[3]);
if (h <0 || h >23 || m <0 || m >59) {
alert ("Invalid time - re-enter it");
input.value = "";
return false;
var f = final[0]+final[1]+":"+final[2]+final[3];
input.value = f;

function strip(which) {
var x = which.value;
x = x.replace(/[^0-9]/g,""); // allow only digits
which.value = x;


<input type = "text" maxlength=5 onkeyup = "strip(this)" ; onblur = "autoTabTimes(this)">

Quizmaster: Three of the four Olympic throwing events are the discus, shot put and the hammer. What is the fourth?
Contestant: Long jump.

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum