Web Development Tutorials




  
  

Checkboxes

The <input type="checkbox"> tag presents a set of checkboxes, any or all of which can be checked to indicate their selection. The general format to create a checkbox is shown below.


<input type="checkbox"
  id="id"
  name="name"
  value="string" checked />

Figure 9-24. General format for a checkbox.

Checkboxes are treated as independent controls, unlike radio buttons which use a common name to enforce a single choice within a group of controls. However, you can assign a common name to simplify processing of a group of checkboxes within an iteration loop. The data value associated with a checkbox is provided in its value attribute. One or more checkboxes can be pre-checked by coding their checked attribute.

The following table lists selected properties and event handlers associated with checkboxes.

Property Description
length The number of checkboxes with the same name.
checked A true or false value indicating whether a box is checked.
status A true or false value indicating whether a box is checked.
value The value attribute coded for a checkbox.
Event Handler Description
onfocus The control gains focus.
onblur The control loses focus.
onclick The checkbox is clicked.

Figure 9-25. Selected properties and event handlers of a checkbox.

You can choose one or more checkboxes to select multiple data values. In the following example, values are reported for checked boxes.

Checkboxes:
 This is Item 1
 This is Item 2
 This is Item 3
 Values are: 

Figure 9-26. Reporting checkbox values.


<script type="text/javascript">
window.onload = init;

function init()
{
   var btnShowValues = document.getElementById("btnShowValue");
   btnShowValues.onclick=showValues;
}

function showValues()
{
   document.getElementById("checkValues").innerHTML = "";
   var checkboxArray = document.getElementName("checkGroup");  
   for (i = 0; i < checkboxArray.length; i++) {
      if (checkboxArray[i].checked == true) {
         document.getElementById("checkValues").innerHTML += checkboxArray[i].value + " ";
      }
   }
} 
</script>

<b>Checkboxes:</b><br>
<input type="checkbox"  name="checkGroup" value="item1"> This is Item 1<br>
<input type="checkbox" name="checkGroup" value="item2"> This is Item 2<br>
<input type="checkbox"  name="checkGroup" value="item3"> This is Item 3<br>
<input type="button" id="btnShowValues" value="Show Values">
<b>Values are: </b><span id="checkValues"></span>

Listing 9-18. Code to report checkbox values.

As with radio buttons, when a checkbox is checked it acquires a checked or status property setting of true. A value can be assigned to a checkbox; otherwise, a checked box is given a default value of "on". To determine which checkboxes have been checked, a loop iterates all checkboxes testing their checked settings. The loop can use the length of all like-named checkboxes as the test value for ending the loop.



TOP | NEXT: Buttons