JavaScript Lesson 20: Using Checkboxes in JavaScript

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInEmail this to someone

<Previous Lesson> [Table of Contents] <Next Lesson>

In this lesson, we shall learn how to write code for checkboxes in JavaScript. 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 format:

<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

<html>
<head>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=windows-1252″>
<title>Item1</title>
</head>
<body>
<script>
function checkstatus()
{ if(MyForm.Checkbox1.checked)
document.write(MyForm.Checkbox1.value+” is selected”);
else
document.write(MyForm.Checkbox1.value+” is not selected”);

}
</script>

<form>
<input value=”Click” onclick=”checkstatus()”>
<input Value=”Item1″>Item1
</form>
</body>

</html>

Click Example 20.1 to try it out.

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

<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=windows-1252″>
<title>JavaScript example 20.2: Multiple Checkboxes</title>
</head>
<body>
<script>
function checkstatus()
{for(count=0;count<4;count++)
{if (MyForm.MyCheckbox[count].checked)
alert(MyForm.MyCheckbox[count].value+” is selected”);
}

}

</script>

<form>
<input value=”Click” onclick=”checkstatus()”><br>
<input Value=”Item1″>Item1<br>
<input Value=”Item2″>Item2<br>
<input Value=”Item3″>Item3<br>
<input Value=”Item4″>Item4<br>
</form>
</body>

</html>

Please click on Example 20.2 to test the output.



<Previous Lesson> [Table of Contents] <Next Lesson>

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInEmail this to someone