Ci ho messo mano di fretta e devi testarla bene bene… Ti dico già che la funzione completeTime() è piuttosto minimale. Cmq… se vuoi anche i secondi puoi fare così:
codice:<!doctype html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Esempio</title> <script type="text/javascript"> function checkTime (oToCheck, oKeyEvent1) { var nChar = oKeyEvent1.charCode, nKey = oKeyEvent1.keyCode, sVal = oToCheck.value, sNewVal = sVal.substring(0, oToCheck.selectionStart - (nKey === 8 && nChar === 0 ? 1 : 0)) + (nChar > 0 ? String.fromCharCode(nChar) : "") + sVal.slice(oToCheck.selectionEnd + (nKey === 46 && nChar === 0 ? 1 : 0)), bFormat = nChar === 0 || /^\d{1,2}(?:\:\d{1,2}){0,2}$/.test(sNewVal); if (bFormat) { var aCorrect = sNewVal.split(":"); for (var nDigit = 0; nDigit < aCorrect.length; nDigit++) { if (parseFloat(aCorrect[nDigit]) > 23 + 36 * nDigit) { bFormat = false; break; } } } return bFormat; } function formatTime (oToFix, oKeyEvent2) { var nKey = oKeyEvent2.keyCode, nSelS = oToFix.selectionStart, nSelE = oToFix.selectionEnd, sVal = oToFix.value, bCheck = nSelS === nSelE && nSelS === sVal.length && nKey !== 8 && nKey !== 46 && (nKey < 32 || nKey > 41); if (bCheck && /^\d{1,2}$/.test(sVal) && (nSelS === 2 || parseFloat(sVal) > 2)) { sVal += ":"; oToFix.value = sVal.replace(/^(\d)\:/, "0$1:"); oToFix.focus(); } else if (bCheck && /^\d\d\:\d/.test(sVal) && (nSelS === 5 || parseFloat(/^\d\d\:(\d)/.exec(sVal)[1]) > 5)) { sVal += ":"; oToFix.value = sVal.replace(/^(\d\d):(\d)(\:|$)/, "$1:0$2$3"); oToFix.focus(); } else if (/\:\d$/.test(sVal) && parseFloat(/\d$/.exec(sVal)) > 5) { oToFix.value = sVal.replace(/\d$/, "0$&"); oToFix.focus(); } } function completeTime (oToFix) { oToFix.value = oToFix.value + "00:00:00".slice(oToFix.value.length); } </script> </head> <body> <form name="myForm"> <input type="text" name="myInput" onkeypress="return checkTime(this,event);" onkeyup="formatTime(this,event);" onblur="completeTime(this);" onpaste="return false;" /></p> </form> </body>![]()

Rispondi quotando