HTML Checkbox Code
This page contains HTML checkbox code. You can copy/paste this code into your own blog or website in order to create checkboxes.
A checkbox is a form element that allows the user to select multiple options from a range of options.
Checkboxes are created with the HTML
<input> tag. Checkboxes can be nested inside a
<form> element or they can stand alone. They can also be associated with a form via the
form attribute of the
Basic Checkbox Example
Here's an example of HTML checkbox code:
|Apple Orange Banana|
Here, we add a submit button so that the checkboxes can become useful. We also place the checkboxes within a
<form> element that specifies a page to process the form.
Checkboxes vs Radio Buttons
It's important to understand the difference between checkboxes and radio buttons. Radio buttons allow the user to select one option only. Checkboxes allow the user to select any number of options.
In the example below, try selecting more than one checkbox. You'll see that you can select as many (or as few) checkboxes as you like. This is how the checkbox element has been designed. It makes the checkbox suitable for times where the user should be able to select multiple options.
Next, try selecting more than one radio button. You'll notice that every time you select another radio button, the previous selection is de-selected. Radio buttons are designed to do this. This helps you enforce users to only select one option. There is no way for them to select multiple options (whether accidentally or intentionally).
In the above example, we enclosed the checkboxes inside a form. HTML5 also allows you to specify a form using the
form attribute. This method could be used in the event that the checkboxes are not inside the form that needs to submit its contents.
In the next example, add
id="myForm" to the form. We then add
form="myForm" to the checkboxes (via the
<input> tags) and move the checkboxes outside of the form. Submitting the form should still submit the contents of the checkboxes, because they reference the
id of the form in their
What would you like for lunch?Apple Orange Banana
Set a Default Value
You can set a default value by using the
checked attribute. When this is added to a checkbox, that checkbox is selected as soon as the page loads (i.e. it doesn't need the user to select it). The user can then choose to "uncheck" that checkbox if so desired, but if they don't it will remain checked (along with any other checkboxes the user checks).
In this example, we've checked the first option.
Choose your free gift:Apple Orange Banana
Disabling a Checkbox
You can disable a checkbox by using the
disabled attribute. You could use this in conjunction with a script to enable/disable the checkbox depending on whether certain criteria has been met.
In this example, we've disabled the second option (Orange).
|Apple Orange Banana|
Also see radio button code for enforcing a single selection.