Validating Radio Buttons

Contact Us or call 1-877-932-8228
Validating Radio Buttons

Validating Radio Buttons

Radio buttons that have the same name are grouped as arrays. Generally, the goal in validating a radio button array is to make sure that the user has checked one of the options. Individual radio buttons have the checked property, which is true if the button is checked and false if it is not. The example below shows a simple function for checking radio button arrays.

Code Sample:

<meta charset="UTF-8">
<title>Radio Arrays</title>
function validate(e){
	var errors = [];
	var f = e.currentTarget;
	              if (!checkRadioArray(f.container) ) {
		errors[errors.length] = "You must choose a cup or cone.";
	if (errors.length > 0) {

function checkRadioArray(radioButtons){
	for (var i=0; i < radioButtons.length; i++) {
		if (radioButtons[i].checked) {
			return true;
	return false;

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];

window.onload = function() {
	document.getElementById("IceCreamForm").addEventListener("submit", function(e){

<h1>Ice Cream Form</h1>
<form method="post" action="Process.html" id="IceCreamForm">
	<strong>Cup or Cone?</strong>
	<input type="radio" name="container" id="Container_Cup" value="cup"> Cup
	<input type="radio" name="container" id="Container_Plaincone" value="plainCone"> Plain cone
	<input type="radio" name="container" id="Container_Sugarcone" value="sugarCone"> Sugar cone
	<input type="radio" name="container" id="Container_Wafflecone" value="waffleCone"> Waffle cone
	<input type="submit" value="Place Order">


Code Explanation

The checkRadioArray() function takes a radio button array as an argument, loops through each radio button in the array, and returns true as soon as it finds one that is checked. Since it is only possible for one option to be checked, there is no reason to continue looking once a checked button has been found. If none of the buttons are checked, the function returns false.

Note that we get the form from the event object e with e.currentTarget, store the form as JavaScript variable f, and then get the radio button set by name (f.container). While not needed in this example, we adopt the common practice of giving radio buttons unique ids, where each id is the shared name, underscore, then unique value, like container_cup. This is useful if we need to refer to a specific radio button.