Looping through radio buttons on a form

A for loop can be very useful when it comes to selecting radio buttons. Take the following sample and its related web page as an example.
See it live

What happens?

When we select a language and click on the submit button, the language is acknowledged below the button.

The idea behind this small script can be applied in many different contexts, right?

I first create a radio button form with the name of “myLang”. Then each button gets a name of “language” and a value of “whateverLanguageName”.

Next we need to loop through each button to see which one is selected.

Finally we assign the innerHTML of some DIV to a string showing the result  we’ve selected.

<form name="myLang">

<input type="radio" name="language" value="English" checked>English
<input type="radio" name="language" value="French">French
<input type="radio" name="language" value="German">German
<input type="radio" name="language" value="Portuguese">Portuguese
<input type="radio" name="language" value="Spanish">Spanish
<input type="button" name="submit" value="submit" onclick="makeSelection()">
<div id="1"></div>
function makeSelection(){
	for (var i = 0; i < document.myLang.language.length; i++) {
			document.getElementById("1").innerHTML = "You've selected " + document.myLang.language[i].value;


For a more detailed explanation on how innerHTML works please refer to my latest eBook at Amazon worldwide:
JavaScript innerHTML: A Project in Three Acts (Small Projects for Mastering JavaScript)

Hope this has some value to you!


Author: tarau

technical writer, web technologies

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s