TUTORIAL 01 –  GETTING A RADIO BUTTON VALUE

 

TUTORIAL DESCRIPTION

 

In this tutorial, we will look at how to get the selected value of a radio button.  Unfortunately, while this seems like it should be very simple, it requires loops to check all the possible answers.

 

Note that if all you need to do is check if one specific answer is selected, then you want to look at tutorial #2.

 

EXAMPLE 01 – CREATING A RADIO BUTTON OBJECT

 

We will start with a form that contains radio buttons. We will use this same form for later examples.

 

Here is the code:

 

<form name="f">

Which one is your favourite?<br>

<input type="radio" name="music" value="Rock" checked="checked">Rock<br>

<input type="radio" name="music" value="Pop">Pop<br>

<input type="radio" name="music" value="Rap">Rap<br>

<input type="radio" name="music" value="Metal">Metal<br>

</form>

 

Click here to see this in action.

 

EXAMPLE 02 – FUNCTION THAT DISPLAYS THE CHOSEN VALUE

 

Unfortunately, we have to write a function that checks the value of the radio buttons. 

 

The function will go through each option in the radio button object and verify to see if it is checked.  If it is checked, it will display the corresponding value on the screen.

 

The following function would check the value of the radio button object created above:

 

<script type="text/javascript">

function getValue()

{

   for (var i=0; i < document.f.music.length; i++)

   {

      if (document.f.music[i].checked)

      {

         alert("You have picked " + document.f.music[i].value);

      }

   }

}

</script>

 

Click here to see this function in action.  Note that a button was added to the form.  When the button is clicked, the function is called.

 

EXAMPLE 03 – CHECKING FOR A SPECIFIC ANSWER (TWO FUNCTIONS)

 

In Example 02, instead of outputting the value of the checked button, we will now return it to where the function was called from. 

 

Instead of calling the function when the button is clicked, we will call the checkAnswers() function. It then makes use of our original function.

 

Here is the code:

 

function getValue()

{

   for (var i=0; i < document.f.music.length; i++)

   {

      if (document.f.music[i].checked)

      {

         return document.f.music[i].value;

      }

   }

}

 

function checkAnswers()

{

   if(getValue() == "Pop")

   {

      alert ("You are correct.");

   }

   else

   {

      alert ("You are wrong.");

   }

}

 

Click here to see this in action.

 

NOTE

 

You have to create a new pair of functions for each radio button object that you create.

 

SIMPLER VERSION

 

If all you need is to verify if one specific answer is taken, then look at tutorial #2.  It’s much simpler but is more limited.