PDA

View Full Version : Javascript checkbox form validation



TonyDevlin
May 27th, 2008, 10:54 AM
Hi I am trying to validate my webpage which has 2 checkboxes on it. I only want the user to select 1 checkbox and if they do select 2 and click submit then an alert box will appear telling them that they have selected 2 boxes. I have managed to make the above happen by having the alert box appear when the 2 checkboxes are selected however the content of the page still gets submitted and moves onto the next page!! How do I stop the page from getting submitted if an alert box appears? I have added my code below.

Thank you.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

<script language="JavaScript" type="text/javascript">
function checkscript() {
if (document.myform.box1.checked == true && document.myform.box2.checked == true)
{ alert('box1 & 2 are selected');
form.email.focus();
return false ;
}

// If the script makes it to here, everything is OK,
// so you can submit the form

else return true;
}

</script>
</head>

<body>

<form name="myform" action="page.html" method="post" onsubmit="return checkscript()">


<input
type="checkbox"
name="box1"
value="yes1">
<input
type="checkbox"
name="box2"
value="yes2">
<input
type="submit">
</form>
</body>
</html>

rangana
May 27th, 2008, 11:02 AM
Should be:


if (document.myform.box1.checked == true && document.myform.box2.checked == true)
{ alert('box1 & 2 are selected');
document.form.email.focus(); // You can remove this part yet.
return false ;
}


...but since you don't have an element whose name is email (yet), this throws an error, which results in your form bein submitted.

The fix is either to have an element with that name or remove that part. ;)

TonyDevlin
May 27th, 2008, 01:05 PM
Thanks for your help, I removed that line, I didnt realise that it was still there, I just needed a couple of fresh eyes to look at it.

:)