Form validation based on radio inputs.

Pure JS approach to form validation based on whether at least one radio button of each group is checked.

by Marventus

HTML

<form id="form1" name="form1" action="#" method="post" onsubmit="return validateForm();"> 
		First time visitor?:<br>
		<div class="question">
			<label for="s1">Yes</label>
			<input type="radio" value="1"> 1 <input type="radio" value="2"> 2 <input type="radio" value="3"> 3 <input type="radio" value="4"> 4 <input type="radio" value="5"> 5 <input type="radio" value="6"> 6 <input type="radio" value="7"> 7 <input type="radio" value="8"> 8 <input type="radio" value="9"> 9 <input type="radio" value="10"> 10 		</div>
				<br>
		<div class="question">
			<label for="s2">No</label>
			<input type="radio" value="1"> 1 <input type="radio" value="2"> 2 <input type="radio" value="3"> 3 <input type="radio" value="4"> 4 <input type="radio" value="5"> 5 <input type="radio" value="6"> 6 <input type="radio" value="7"> 7 <input type="radio" value="8"> 8 <input type="radio" value="9"> 9 <input type="radio" value="10"> 10 		</div>
				<br>
		<div class="question">
			 <label for="s3">Cool</label>
			<input type="radio" value="1"> 1 <input type="radio" value="2"> 2 <input type="radio" value="3"> 3 <input type="radio" value="4"> 4 <input type="radio" value="5"> 5 <input type="radio" value="6"> 6 <input type="radio" value="7"> 7 <input type="radio" value="8"> 8 <input type="radio" value="9"> 9 <input type="radio" value="10"> 10 		</div>
				<br> 
		<input type="submit" value="Submit"><br>
</form>

JavaScript

function validateForm() {
		var questions = document.getElementsByClassName("question"),
			formValid = true;
		for( var j=0; j<questions.length; j++ ) {
			if( !isOneInputChecked(questions[j], "radio") ) {
				formValid = false;
			}
		}
		alert(formValid ? "Submission Succesfull!" : "Submission Failed!");
		return formValid;
	}
	function isOneInputChecked(sel) {
        /* Based on code by Michael Berkowski
         * Ref: http://stackoverflow.com/questions/13060313/checking-if-at-least-one-radio-button-has-been-selected-javascript#answer-13060348
        */        
		// All <input> tags...
		var inputs = sel.getElementsByTagName('input');
		for (var k=0; k<inputs.length; k++) {
			// If you have more than one radio group, also check the name attribute
			// for the one you want as in && chx[i].name == 'choose'
			// Return true from the function on first match of a checked item
			if( inputs[k].checked )
				return true;
		}
		// End of the loop, return false
		return false;
	}