MediaZeal Web Design: Tips & Tricks
Home
Services
Pricing
Portfolio
Worksheet
Contact


JavaScript Checkbox Validation
Use this Validator to Require a Checkbox in your forms
MediaZeal Web Design

MediaZeal will gladly help you with JavaScript problems. Learn more about our JavaScript Solutions.
Feel free to link to this article. If you copy it to post on your site in full or in part,
please include a credit and link to MediaZeal Web Design Tips & Tricks.

JavaScript is a natural for form validation. This simple script allows you to require that a checkbox is checked for the form to submit. One of the great things about setting up the checkbox validation this way is that it does not clear the form, so no information is lost.


Name:
Email:
Comments: Was this helpful?
I agree to the terms
  
Click on the submit button to the left without checking that you agree to the terms. You will be prompted to check the required checkbox or the form will not process.

There is a JavaScript called on submit that says "if the form's agree field is not checked, then give the message that info is missing." In JavaScript that reads like this:
if (!document.form.agree.checked) {
  missinginfo += "\n - You must agree to the terms";
}
Here's How to Do It

Paste this code into the head section
<!-- This script is available free online at MediaZeal Web Design --->
<!-- http://mediazeal.com --->


<script language="JavaScript" type="text/JavaScript">
<!--//hide script
function checkme() {
missinginfo = "";
if (!document.form.agree.checked) {
missinginfo += "\n - You must agree to the terms";
}
if (missinginfo != "") {
missinginfo ="__________________________________\n" +
"Required information is missing: \n" +
missinginfo + "\n__________________________________" +
"\nPlease complete and resubmit.";
alert(missinginfo);
return false;
}
else {
return true;
}
}

// --->
</script>


Paste this code into the body section
<form name="form" method="post" action="#" onSubmit="return checkme();">
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td>Name: </td>
<td> <input type="text" size="20" name="name"></td>
</tr>
<tr>
<td>Email: </td>
<td> <input type="text" size="20" name="email"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="checkbox" name="agree" value="agree_terms"> I agree to the terms</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="submit" value="Submit">  <input type="reset" name="reset" value="Clear"></td>
</tr>
</table>
</form>



Feel free to link to this article. If you copy it to post on your site in full or in part, please include a credit and link to MediaZeal Web Design Tips & Tricks.
link to MediaZeal home page

© 2000-2007 MediaZeal Web Design, Sacramento :: Site map