Input tags with the type attribute checkbox can be grouped like radio buttons so that several checkboxes have the same name. However, any number of checkboxes can be selected by the user. Working with checkboxes in JavaScript is similar to but not exactly the same as working with radio buttons. Here is a short example that demonstrates getting values from checkboxes and radio buttons in the same form:
A series of checkboxes with the same name are reflected as an array of checkbox objects. In this example each check box input tag is named Music
but has a different value. Since there are identically named input tags of the same type, an array of checkbox objects named Music
is created. When the button in this form is pressed, it passes a reference to the form to a function named, in this case, showBoxes(frm)
. The function loops through the checkbox array within the form. To access the check box array from the form reference it is only necessary to append the name of the checkboxes to the form reference:
frm.Music
For example to access the number of elements in the array:
frm.Music.length
or if the variable i
contains the index of one of the elements, here is how you would check to see if that element had been checked:
if (frm.Music[i].checked)
or get that element's value:
frm.Music[i].value
Since many values may be checked, this example gathers the values from each by appending each value on to the end of a string. Since the string is eventually displayed in an alert dialog each value is separated by a "\n", or new line character. In this case the string is named message
message = message + frm.Music[i].value + "\n"
Here is the complete page: