Javascript: Looping through radio buttons without jQuery

There are times when you don’t have access to a third-party library such as jQuery to make life easy and those are the times where you regret not paying any attention to how actual javascript works. Going through radio buttons with jQuery is very easy, but with javascript it is a little bit more unclear if you haven’t done it before.

I’m going to show you a very simple example where I have four radio buttons and I want to know which one is selected:


<!DOCUMENT html>
		<title>Javascript Radio Button Demo</title>
		<script type="text/javascript" src="MyScript.js"></script>
		<h1>My Form with radio buttons!</h1>
		<form id="MyForm" name="MyForm" action="#" method="GET">
			<p><input type="radio" name="direction" value="north"> North</p>
			<p><input type="radio" name="direction" value="east"> East</p>
			<p><input type="radio" name="direction" value="south"> South</p>
			<p><input type="radio" name="direction" value="west"> West</p>
			<p><input type="submit" name="submit" value="Submit"></p>


window.onload = function()
	//Fetch the form element
	var form = document.getElementById("MyForm");
	//Bind the 'onsubmit' event to an anonymous function
	form.onsubmit = function()
		//Find out how many radio buttons you have
		var numberOfDirections = form.direction.length;
		//Loop through the radio buttons
		for(var i = 0; i < numberOfDirections; i++)
			//Select a radio button
			var direction = form.direction[i];
			//Check if the radio button is checked
				alert("You selected " + direction.value);
		return false;

What is important is that the name-tag is the same for all radio buttons that are considered to be part of the same group. This way the document-object will generate array properties in the form-objects for the radio buttons. As we loop through that array we can check if the radio button checked-property is true. If it is, we found the checked radio button.