JavaScript Lesson 19: The Radio Button

<Lesson 18> [Table of Contents] <Lesson 20>

In this lesson, we shall learn how to write code for radio buttons in JavaScript. The function of the radio buttons is to let the user select one item from a group of items. Radio buttons does not allow the user to select more than one item. There should be at least two radio buttons on a form. Once the user clicks on a radio button, he or she cannot unclick it.

19.1 Using the radio button

In this example, the user is presented with four types of fruits and he or she can choose only one type at one time by clicking the radio button beside the label of a particular fruit. The code is as follow:



Example 19.1: Code for Item Selection

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>JavaScript Example 19.2</title>
</head>
<body>
<script>
function checkItem()
{for(count=0;count<4;count++)
{if (MyForm.item[count].checked)
alert(MyForm.item[count].value+" is selected");
}
}
</script>
<form>
<input value="Select and Click" onclick="checkItem()"><br>
<input value="Apple">
<label>Apple</label><br>
<input value="Orange">
<label>Orange</label><br>
<input value="Grape">
<label>Grape</label><br>
<input value="Melon">
<label>Melon</label><br>
</form>
</body>

</html>

Click Example 19.1 to try it out.

Example 19.2: Load Image of Choice

You can modify the above program by asking the user to select an image of his or her choice. Here I have designed six images representing the faces of a dice.

<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>JavaScript Example 19.2</title>
</head>
<body>
<script>
function checkItem()
{for(count=0;count<6;count++)
{if (MyForm.item[count].checked)
document.write ( "<img src = \"" +
(Math.round(count)+1)+
".jpg\" width = \"50\" height = \"50\" />");

}
}
</script>
<form>
<input value="Select and Click" onclick="checkItem()"><br>
<input value="One">
<label>One Dot</label><br>
<input value="Two">
<label>Two Dots</label><br>
<input value="Three">
<label>Three Dots</label><br>
<input value="Four">
<label>Four Dots</label><br>
<input value="Five">
<label>Five Dots</label><br>
<input value="Six">
<label>Six Dots</label><br>

</form>
</body>

</html>

Please click on Example 19.2 to test the output.


<Lesson 18> [Contents] <Lesson 20>

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on Reddit