How to Make a Checkbox Required on an Email Form
If your Web page contains an email form, you may wish to prevent users from submitting it until they perform certain tasks. A common task is checking a checkbox. You have probably seen sites that require you to agree to some terms by checking a checkbox. Until you do that, you cannot submit the form. HTML alone cannot tell if a checkmark exists inside a checkbox. You must use a scripting language to perform this task. By adding an "onsubmit" event to your email form, you can prevent form submission until users check your checkbox.
Instructions
-
-
1
Launch an HTML editor and open a Web document that has an email form. Locate the form's HTML code. It will probably look similar to the code shown below:
<form name="emailForm" action="processForm.php"
method="post">
Name: <input type="text" name="name">
Email Address: <input type="text" name="emailAddress">
<input type="submit" value="Submit Email">
</form>
The opening "<form" tag, shown on line 1, defines the form. The closing "</form>" tag ends the form declaration. Paste the following text after the closing "</form>" tag:
<input id="Checkbox1" type="checkbox" />
This adds a checkbox whose ID is "Checkbox1."
-
2
Modify the opening "<form" tag by appending the following text to the end of that tag declaration:
onsubmit="return validateForm('Checkbox1')"
This "onsubmit" attribute tells browsers to call the JavaScript function named "validateForm" before submitting the form. This attribute passes the ID of the checkbox you wish to validate. After appending this text to your form's opening "<form " tag, that tag's code may appear as shown below:
<form name="emailForm" action="processForm.php"
method="post" onsubmit="return validateForm('Checkbox1')">
-
-
3
Add this "validateForm" function to your document's "script" section:
function validateForm(checkboxID) {
var checkbox = document.getElementById(checkboxID);
if (checkbox.checked == false) {
alert("Please check the checkbox");
return false;
}
else
return true;
}
This function, called by the form's "onsubmit" event, examines the checkbox's "checked" state. If it discovers that the check state is false, it displays an error message and asks the user to place a check in the checkbox. Otherwise, the function returns a value of "true" to the form.
-
4
Save the document, and open it in a browser. Click the form's submit button without placing a checkmark in the checkbox. The validation function runs and displays the "Please place a check in the checkbox" message.
-
5
Click the checkbox to add a checkmark to the checkbox, and click the button again. The page submits your email form.
-
1
Tips & Warnings
Note that the ID value you pass to the "validateForm" function must be the same as the ID of the checkbox you wish to verify. The function needs that ID in order to examine its checked state.
References
Resources
- Photo Credit John Foxx/Stockbyte/Getty Images