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:
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
In this example, the user can verify whether a checkbox is checked or not.
<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:
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.
<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>
Copyright©2008 Dr.Liew Voon Kiong. All rights reserved |Contact|Privacy Policy