If you only care to check if
one radio button option was chosen or not, then this tutorial is for you. It is very easy to do.
This would work if you are
creating an online quiz and only care to check if the correct answer is chosen
or not. Note that you would not be able
to check which wrong answer was chosen.
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
of the following types of music are also a beverage?<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.
OPTION INDEX
NUMBER
All options are numbered by
an index. Note that indexes start at
0 instead of at 1.
The first option is
Rock. It has index 0.
The next option is Pop. It has index 1.
The next option is Rap. It has index 2.
The last option is
Metal. It has index 3.
EXAMPLE 02 –
FUNCTION THAT CHECKS ANSWER
The correct answer has index
number 1. So we will verify if that
option is checked.
We do so where you see the
red number 1. If you’d want to check
for a different index number, you’d simply replace the 1 by that number.
function
checkAnswers()
{
var correct = 0;
if(document.f.music[1].checked == true)
{
correct = correct + 1;
}
alert("You scored " + correct +
" out of 1.");
}
Click here to see all of this in action.
EXAMPLE 03 –
MULTIPLE RADIO BUTTON OBJECTS
Click here to see this work. View source to see all the code.