JavaScript Tutorial JavaScript Examples CSS Tutorial HTML Tutorial About Us

Lesson 20: The Checkbox


In this lesson, we shall learn how to write code for the JavaScript checkbox. Checkboxes are differently from radio buttons. While radio buttons only allow the user to select one option at a time, checkboxes allow the users to select multiple options. You can try to click on the radio buttons and the checkboxes below:

Item1 Item2 Item3 Item4 Item5
Item1 Item2 Item3 Item4 Item5

The status of a checkbox is either check or unchecked. A checkbox can be created in a web page using the following syntax:

<input type="checkbox" name="Checkbox1" value="chkbox1">Item1

20.1 Using the checkboxes

In this example, the user can verify whether a checkbox is checked or not.

Example 20.1: Code for Item Selection

<script>
function checkstatus()
{ if(MyForm.Checkbox1.checked)
document.write(MyForm.Checkbox1.value+" is selected");
else
document.write(MyForm.Checkbox1.value+" is not selected");

}
</script>

Also create a checkbox as follows:

<form>
<input value="Click" onclick="checkstatus()">
<input Value="Item1">Item1
</form>

Try out the JavaScript by clicking the button below:

Item1

You can modify the above program by adding more than one checkboxes to the page. The code is able to show the user how many checkboxes are being selected.

Example 20.2: To Check Status of Multiple Checkboxes


<script>
function checkstatus1()
{for(count=0;count<4;count++)
{if (MyForm.MyCheckbox[count].checked)
alert(MyForm.MyCheckbox[count].value+" is selected");
}

}

</script>

<form name="MyForm2">
<input type="button" value="Click" onclick="checkstatus1()"><br>
<input type="checkbox" Value="Item1">Item1<br>
<input type="checkbox" Value="Item2">Item2<br>
<input type="checkbox"Value="Item3">Item3<br>
<input type="checkbox"Value="Item4">Item4<br>
</form>
</body>

</html>

Item1
Item2
Item3
Item4


❮ Previous Lesson Next Lesson ❯


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