Radio Buttons or checkboxes?
Radio buttons and checkboxes allow users to select values with a click of the mouse. Radio buttons appear as a small circular option on a page. Checkboxes appear as a small square on a page.
Checkboxes are different from radio buttons because radio buttons allow users to select an option from various options, thus allowing the user to select a choice based on an either/or option whereas checkboxes allow a user to select more than one option at a time.
The checkbox object allows you to create checkboxes within your HTML forms. Checkboxes allow the user to select one or more options from a limited number of choices. The checkbox allows you to search for elements within the checkbox as elements of an array. You can also search for elements of a checkbox using the documents.getElementById() method.
The Checkbox object properties include:
checked – the checked properties sets or returns the state of the checkbox
defaultChecked – this property returns the default value of the checked attribute
disabled – this property returns whether the checkbox object is disabled or not
name – used to set the name of the object or return the name
value – sets the value of the object or returns the value
How to use the Checkbox object to create a checkbox in your form
Here is the sample code you could use:
The above code creates a page with the following elements:
When the user clicks the checkbox, the onClick event runs the function to determine if the checkbox is clicked on not.
The first time the user clicks it, the output will look like this:
The second time the user selects the checkbox next to the select option, the check mark will be removed so the output will look like this:
Example of using Checkbox checked with multiple checkboxes
Our next code example will show you how to use the checkbox checked property with multiple checkboxes to confirm a client’s order.
Here is the code we will use for this example:
The form for the above code looks like this:
The code also creates a function that checks the “checked” status of each checkbox to see if the user has selected the checkbox or not. If the checkbox checked status is true then the function creates an alert for that item. Assuming the client selects “Coffee” and “Milk” by selecting the two checkboxes next to those items the user will receive the following alerts:
As you can see from the above examples, including checkboxes in your web pages is easy. The checked property allows you to set the checkbox initial value or return the value if the user has selected the checkbox or not.