Click to See Complete Forum and Search --> : Time Script


The-Morg
11-30-2003, 05:16 PM
Hey-

New to the forum, just had a question about a simple little validation script for user entered time. The script checks for a colon (:) somewhere in the time which the user enters.

The problem is that I get no window alert even if I do not use a colon.

It is probably something simple that I am overlooking... anyone see it?

<html>

<head>

<title>Project 14-1</title>

<script language="JavaScript">
<!--

function checkTime()
{
var result=true;

if (document.form1.theTime.value.indexOf(":") == -1)
{
result=false;
window.alert("Sorry, your time must contain a colon /(:/), please try again.");
}
return result;
}

//-->
</script>

</head>


<body onLoad="document.form1.theTime.focus();">

<form name="form1" action="#">

What time is it?<br>
<input type="text" name="theTime"><p>
<input type="submit" value="Submit" name="submitForm" onSubmit="return checkTime();">

</form>

</body>


</html>



Thanks guys!

pyro
11-30-2003, 06:07 PM
As a bare minimum answer, the onsubmit event handler needs to go in the <form> tag.

As a better answer, use something like this:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Project 14-1</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
function checkTime(frm) {
if (frm.theTime.value.indexOf(":") == -1) {
alert("Sorry, your time must contain a colon (:), please try again.");
return false;
}
else {
return true;
}
}
</script>
</head>
<body onload="document.form1.theTime.focus();">
<form name="form1" action="#" onsubmit="return checkTime(this);">
<p>What time is it?<br>
<input type="text" name="theTime"></p>
<p><input type="submit" value="Submit" name="submitForm"></p>
</form>
</body>
</html>Also, if you need to do any serious validation, you are going to want to look into regular expressions.

The-Morg
11-30-2003, 07:24 PM
Hey, looks good. Thanks for your help pyro!

pyro
11-30-2003, 08:02 PM
Happy to help. :)