JavaScript Tutorial JavaScript Examples CSS Tutorial HTML Tutorial About Us

Lesson 19: Radio Button


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: JavaScript 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 we have designed six images representing the faces of a dice.

We used the if statement to load the image according to the index of the item selected. The JavaScript is as follows:


<script>
function checkItem()
{for(count=0;count<6;count++)
{if (MyForm.item[count].checked)
num=(Math.round(count)+1);
var myimg = document.getElementById("myimage");
myimg.src=num+".jpg";
}
}
</script>

Besides that, you need to create the following radio buttons.

<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>

Try to change the image by clicking on the radio buttons.













❮ Previous Lesson Next Lesson ❯


Copyright©2008 Dr.Liew Voon Kiong. All rights reserved |Contact|Privacy Policy