- Checkboxes
- Checked or not checked?
- Multiple choices
- Labels for checkboxes
- Working dynamically with a checkbox
- Summary
- How to create and use a HTML checkbox ?
- Base Demo
- Syntax
- Value
- Default
- If Set
- Visual / Styling
- Css
- Switch
- Button
- Keyboard Navigation
- How to
- How to change the state programmatically
- How to use a checkbox to enable or disable other Form elements
- Aria Role
- Documentation / Reference
- How TO — Custom Checkbox
- How To Create a Custom Checkbox
- Example
- Example
- How To Create a Custom Radio Button
- Example
Checkboxes
Using checkboxes is a good option when you want to give your visitors the option to choose several items from a group of choices. In that regard, the checkbox works opposite of a radio button, which only allows you to select one item from a group of choices. In its most simple form, a checkbox is simply an input element with the type property set to checkbox, like this:
However, as with all input elements, you need to define a name for it to be usable — without a name, the element won’t be identifiable when posting the form back to a server for processing. You also want to set a value — this will be the value sent to the server if the checkbox has been checked. Here’s an example:
With this example, if the checkbox has been checked and the form is submitted to a server, the server will be able to read the form element «nameOfChoice» and its value will be 1.
Checked or not checked?
Notice how all the checkboxes so far have not been checked from the beginning — the user would have to interact with the checkbox to change its state from unchecked to checked. This might be what you want, but sometimes, you want the checkbox to be checked by default, either to suggest a choice to the user or because you are showing a checkbox with a value that corresponds to an existing setting, e.g. from a database. Fortunately, this is very simple — just add the checked attribute to the checkbox:
In the old days of XHTML, where each attribute should always have a value, even the boolean attributes, it would look like this:
Either way should work in all modern browsers, but the first way is shorter and more «HTML5-like».
Multiple choices
So far, all our checkboxes have been simple switches, e.g. for defining whether an option is on or off. Checkboxes are great for that, but as mentioned, they can also be used to allow the user a selection of possible options. Let me show you a neat example where this makes sense:
Cats
Dogs
Birds
Notice how we now have multiple checkboxes, but they all share the same name («favorite_pet») but different values (e.g. «Dogs»). When this form is submitted back to the server, all these checkboxes will be represented by a single name, but the value will be an array of 0-3 items. If you had used radio buttons instead of checkboxes, the user would only be allowed to pick a single favorite animal, but with checkboxes, they can select none of them, all of them or some of them.
Labels for checkboxes
If you tested the previous example, you will notice that we can put text next to a checkbox, but they are still two separate things — you can’t click the text to trigger the checkbox. This can be really annoying for the user, but fortunately for us, it’s easy to solve: Just use the label element! Here’s a basic example to show you the difference:
Two checkboxes — one without a label and one with. They might look almost identical, but the one with the label can be triggered by clicking both the actual checkbox and the attached label. This is nice if you’re sitting on a desktop PC with a mouse, but even better when you’re using a touch device like a smartphone, where small checkboxes can be hard to hit with your finger.
The label is very simple — it uses the for attribute to attach itself to a form element with a matching id attribute (notice how I have «dogs» in both places).
Working dynamically with a checkbox
Just like any other DOM element, you are able to manipulate a checkbox using JavaScript. In that regard, it could be interesting to check whether a checkbox is checked or not and perhaps add some logic to control how many options a user can select. To show you how this can be done, I have extended a previous example (the «Favorite Pet» selector) to include some JavaScript magic:
Cats
Dogs
Birds
function ValidatePetSelection()
<
var checkboxes = document.getElementsByName("favorite_pet");
var numberOfCheckedItems = 0;
for(var i = 0; i < checkboxes.length; i++)
<
if(checkboxes[i].checked)
numberOfCheckedItems++;
>
if(numberOfCheckedItems > 2)
<
alert("You can't select more than two favorite pets!");
return false;
>
>
Allow me to quickly run through what this code does. We have the same form as before, but we have added an event handler to each of the checkboxes, which causes them to call a JavaScript function (ValidatePetSelection) when the user clicks them. In this function, we get a hold of all the relevant checkboxes using the getElementsByName function and then we loop through them to see if they are checked or not — for each checked item, we add to a number. This number is then checked and if it exceeds two, then we alert the user about the problem (only two pets can be selected) and then we return false. Returning false will prevent the checkbox from being checked.
This was just a simple example of how to work with checkboxes using JavaScript. You can do much more, especially if you use a JavaScript framework like jQuery, which will make it a lot easier to select and manipulate DOM elements.
Summary
Checkboxes allow you to setup selectable options for your users — either to toggle a single setting on or off, or to allow for multiple choices, like in the Favorite Pet example. You should use labels to tie your checkbox and the descriptive text together, to allow the user to click a larger area when manipulating the checkbox — this is also good for assisting technologies like screen readers for visually impaired.
Is your preferred language not on the list? Click here to help us translate this article into your language!
How to create and use a HTML checkbox ?
The HTML checkbox form control can only have two checked states (via its checked attribute):
If you want to get always a value for a property (ie false or true), you can:
Base Demo
This demo shows that if the checkbox is checked, the property given by the name attribute (with value property-name ) will be added to the data send by the form with the default value of on
Syntax
The syntax of a checkbox is:
checked is the optional checked attribute (default to false ) that sets the state of the checkbox (How to change it programmatically)
Value
If a checkbox is unchecked when its form is submitted, the field data is just not sent.
There is no not-checked value
Default
The default value is on and never changes.
document.querySelector("input").addEventListener("click", function()< console.log(`The checkbox is checked ? $`); console.log(`The value is $`); >);
If Set
If the value attribute is set, this value will be send instead
document.querySelector("form").addEventListener("submit", function(event)< event.preventDefault(); let formData = new FormData(this); let i = 0; for (let entry of formData) < i++; console.log(`Entry $`); console.log(entry); > console.log(`Number of field sent: $`); >);
Visual / Styling
Css
Switch
Button
Keyboard Navigation
You may navigate with the tab key because a input (and alos checkbox) is by default focusable. You still may change the order of navigation via the tabindex value.
the third tab will get you on the next interactive element in the iframe (ie a link) — the code is rendered in a iframe
How to
How to change the state programmatically
The checked attribute of the input checkbox element permits:
function toggleCheckBox(event) < event.preventDefault(); if (event.target.checkbox.checked)< event.target.checkbox.checked = false; event.target.button.innerHTML= "Check the checkbox"; >else < event.target.checkbox.checked = true; event.target.button.innerHTML= "Uncheck the checkbox"; >>
How to use a checkbox to enable or disable other Form elements
Example of a legend with a checkbox that controls whether or not the fieldset is enabled
Aria Role
With aria role, you need to handle programmatically the state of each attribute as seen in this example 3)
[role='checkbox'][aria-checked='false']:before < content: '\00a0\00a0'; width: 14px; height: 14px; border: 1px solid hsl(0, 0%, 66%); border-radius: 0.2em; background-image: linear-gradient(to bottom, hsl(300, 3%, 93%), #fff 30%); >[role='checkbox'][aria-checked='true']:before < content: url('/_media/web/html/checkbox_checked.png'); >[role='checkbox'].focus
Sandwich Condiments Lettuce Tomato Mustard Sprouts
Documentation / Reference
FormData is a web api object that represent the data of a form that should be send if the form is submited. Therefore if you have a checkbox that is not checked, formdata will not collect it. You can.
checked is an HTML attribute that indicates via its value (true or false — default to true) if the form control element is checked. It’s used: in a checkbox or radio button select optionselected.
control form elements are element that are used specifically inside a form. They are used: to specify a key and a value. to layout the form to submit or reset it field set [optional] that.
An inputinput element of a form control that permits to define a scalar value inputFull list Ref Doc The type attribute defined: the default behavior the design of the element. and the.
HTML The label html element represents a caption for a control item in a form (user interface). idfor A click on the label: will bring focus on the control element. propagates to the control.
legend is an element that represents a caption for the fieldset element. Example of a legend with a checkbox that controls whether or not the fieldset is enabled .
A radio represents a serie of mutually-exclusive choices in a form. It is an input element of type radio. A radio is round to distinguish from the square checkbox. As the checkbox, the state.
This page shows you how you can create a checkbox in React. This example is written in JSX and shows you a controlled component. The react forms components input accept a value attribute that is used.
How TO — Custom Checkbox
Learn how to create custom checkboxes and radio buttons with CSS.
Custom checkbox:
Custom radio button:
How To Create a Custom Checkbox
Step 1) Add HTML:
Example
Step 2) Add CSS:
Example
/* Customize the label (the container) */
.container display: block;
position: relative;
padding-left: 35px;
margin-bottom: 12px;
cursor: pointer;
font-size: 22px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
>
/* Hide the browser’s default checkbox */
.container input position: absolute;
opacity: 0;
cursor: pointer;
height: 0;
width: 0;
>
/* Create a custom checkbox */
.checkmark position: absolute;
top: 0;
left: 0;
height: 25px;
width: 25px;
background-color: #eee;
>
/* On mouse-over, add a grey background color */
.container:hover input ~ .checkmark background-color: #ccc;
>
/* When the checkbox is checked, add a blue background */
.container input:checked ~ .checkmark background-color: #2196F3;
>
/* Create the checkmark/indicator (hidden when not checked) */
.checkmark:after content: «»;
position: absolute;
display: none;
>
/* Show the checkmark when checked */
.container input:checked ~ .checkmark:after display: block;
>
/* Style the checkmark/indicator */
.container .checkmark:after left: 9px;
top: 5px;
width: 5px;
height: 10px;
border: solid white;
border-width: 0 3px 3px 0;
-webkit-transform: rotate(45deg);
-ms-transform: rotate(45deg);
transform: rotate(45deg);
>
How To Create a Custom Radio Button
Example
/* Customize the label (the container) */
.container display: block;
position: relative;
padding-left: 35px;
margin-bottom: 12px;
cursor: pointer;
font-size: 22px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
>
/* Hide the browser’s default radio button */
.container input position: absolute;
opacity: 0;
cursor: pointer;
height: 0;
width: 0;
>
/* Create a custom radio button */
.checkmark position: absolute;
top: 0;
left: 0;
height: 25px;
width: 25px;
background-color: #eee;
border-radius: 50%;
>
/* On mouse-over, add a grey background color */
.container:hover input ~ .checkmark background-color: #ccc;
>
/* When the radio button is checked, add a blue background */
.container input:checked ~ .checkmark background-color: #2196F3;
>
/* Create the indicator (the dot/circle — hidden when not checked) */
.checkmark:after content: «»;
position: absolute;
display: none;
>
/* Show the indicator (dot/circle) when checked */
.container input:checked ~ .checkmark:after display: block;
>
/* Style the indicator (dot/circle) */
.container .checkmark:after top: 9px;
left: 9px;
width: 8px;
height: 8px;
border-radius: 50%;
background: white;
>