Click to See Complete Forum and Search --> : Javascript Error


Force
07-22-2003, 10:39 AM
I have the following javascript fired by the onsubmit event. The purpose is to validate that required fields have been filled in. The alert fires okay, but when I click the okay button, rather than take the user back to the field with the error, it submits the form to the database. I'm fairly new to Javascript and don't see the problem.
Thanks for the help.

<script language="JavaScript">
function doublecheck(){
if (document.myform.fname.value == "")
{
alert('First Name is a required field');
myform.fname.focus();
myform.fname.select();
return false;
}
return false;
}
</script>

here is how I'm calling it.

<FORM ACTION="Process.cfm" enctype="multipart/form-data" METHOD="post" name="myform" onsubmit="doublecheck();">

requestcode
07-22-2003, 11:07 AM
Change your onSubmit to this:
onsubmit="return doublecheck();">

Force
07-22-2003, 05:42 PM
requestcode,

Thanks for the help. That did the trick. Now I'm having a tough time getting the script to work when I try to use if-else statements.

The following code works well if I drop off the phone validation. It will validate the first and last name. If I leave it on, it blows right through the script without validating anything. I'm guessing that I've got an extra }, but I don't see it.
Thanks for the help. I'll pass this knowledge on when I get to know the language better.

<script language="JavaScript">
function doublecheck(){
if (document.myform.fname.value == "")
{
alert('First Name is a required field');
myform.fname.focus();
myform.fname.select();
return false;
}else{
if (document.myform.lname.value == "")
{
alert('Last Name is a required field');
myform.lname.focus();
myform.lname.select();
return false;
}
}else{
if (document.myform.phone.value == "")
{
alert('Phone is a required field');
myform.phone.focus();
myform.phone.select();
return false;
}
}
}

</script>

skriptor
07-23-2003, 01:48 AM
Hi,
moving a bracket should solve your problem:

<script language="JavaScript">
function doublecheck(){
if (document.myform.fname.value == "") {
alert('First Name is a required field');
myform.fname.focus();
myform.fname.select();
return false;
}else{
if (document.myform.lname.value == "") {
alert('Last Name is a required field');
myform.lname.focus();
myform.lname.select();
return false;
}else{
if (document.myform.phone.value == "") {
alert('Phone is a required field');
myform.phone.focus();
myform.phone.select();
return false;
}
}
}
}
</script>

Good luck, skriptor