Validating Check Boxes

Welcome to our free JavaScript tutorial. This tutorial is based on Webucator's Introduction to JavaScript Training course.

Contact Us or call 1-877-932-8228
Validating Check Boxes

Validating Check Boxes

Like radio buttons, check boxes have the checked property, which is true if the button is checked and false if it is not. However, unlike radio buttons, check boxes are not stored as arrays. The example below shows a simple function for checking to make sure a check box is checked.

Code Sample:

FormValidation/Demos/CheckBoxes.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Checkboxes</title>
<script>
function validate(e){
	var errors = [];
	
	if ( !checkCheckBox(document.getElementById("terms")) ) {
		errors[errors.length] = "You must agree to the terms.";
	}
	
	if (errors.length > 0) {
		reportErrors(errors);
		e.preventDefault();
	}

}function checkCheckBox(cb){
	return cb.checked;
}

function reportErrors(errors){
	var msg = "There were some problems...\n";
	var numError;
	for (var i = 0; i<errors.length; i++) {
		numError = i + 1;
		msg += "\n" + numError + ". " + errors[i];
	}
	alert(msg);
}

window.onload = function() {
	document.getElementById("noicecreamform").addEventListener("submit", function(e){
    	validate(e);
	});
}
</script>
</head>
<body>
<h1>Ice Cream Form</h1>
<form method="post" action="Process.html" id="noicecreamform">
	<input type="checkbox" name="terms" id="terms">
	I understand that I'm really not going to get any ice cream.
	<br><br>
	<input type="submit" value="Place Order">
</form>

</body>
</html>

Code Explanation

Next

This tutorial is based on Webucator's Introduction to JavaScript Training Course. We also offer many other JavaScript Training courses. Sign up today to get help from a live instructor.