How to create and use a HTML checkbox ?

Html Checkbox Illustration

About

Checkbox is a type of input element that will add its name and value to the form data only if checked (making it a succesful control)

The HTML checkbox form control can only have two checked states (via its checked attribute):

  • checked (checked=true)
  • or not checked (checked=false)

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

  • The HTML: A checkbox with the mandatory name (property-name)
<form>
    <input type="checkbox" name="property-name"  />
    <button type="submit">Submit</button>
</form>
  • Test it:
    • Uncheck and submit
    • Check and submit

Syntax

The syntax of a checkbox is:

<input type="checkbox" name="propertyName" value="propertyValue" checked="false|true"/>

where:

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.

Demo:

  • The HTML
<input type="checkbox"  name="indicator"/>
document.querySelector("input").addEventListener("click", function(){
   console.log(`The checkbox is checked ? ${this.checked}`);
   console.log(`The value is ${this.value}`);
});
  • Checking or unchecking the checkbox does not change the value

If Set

If the value attribute is set, this value will be send instead

Demo:

  • The HTML with a checkbox with a mandatory name and a custom value
<form>
    <input type="checkbox" name="indicator" value="customValue" />
    <button type="submit">Submit</button>
</form>
  • This javascript:
    • will intercept the submit event,
    • create a formdata to capture the fields send.
    • and logs the entries.
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 ${i}`);
      console.log(entry);
   }
   console.log(`Number of field sent: ${i}`);
});
  • The result:
    • Uncheck and submit
    • Check and submit

Visual / Styling

Css

  • To style the below checkbox:
<input type="checkbox"  name="indicator" checked/>
  • first disable the browser rendering
input[type="checkbox"] {
  appearance: none;
}
  • Then make you own.
  • Styling for Checked or unchecked checkbox
input[type="checkbox"] {
  width: 2rem;
  height: 2rem;
  border-radius: .5em;
  border: 1px solid rgba(0,0,0,.25);
  background-color: #20c997;
  border-color: #20c997;
}
input[type="checkbox"]:checked {
  background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='%23fff' viewBox='0 0 16 16'%3e%3cpath d='M10.97 4.97a.75.75 0 0 1 1.07 1.05l-3.99 4.99a.75.75 0 0 1-1.08.02L4.324 8.384a.75.75 0 1 1 1.06-1.06l2.094 2.093 3.473-4.425a.267.267 0 0 1 .02-.022z'/%3e%3c/svg%3e");
}
  • Output:

Switch

As switch 1)

<div class="form-check form-switch">
  <input class="form-check-input" type="checkbox" id="flexSwitchCheckChecked" checked>
  <label class="form-check-label" for="flexSwitchCheckChecked">Checked switch checkbox input</label>
</div>

Button

With button 2)

<input type="checkbox" class="btn-check" id="btn-check-2" checked autocomplete="off">
<label class="btn btn-primary" for="btn-check-2">Checked</label>

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.

Example:

  • if you click on the first check below
  • the first tab will get you on the last one because of the tabindex of value 2
  • the second tab will get you on the second checkbox because of the tabindex of value 0
  • the third tab will get you on the next interactive element in the iframe (ie a link) - the code is rendered in a iframe
<input type="checkbox"  tabindex="1" />
<input type="checkbox" tabindex="0" />
<input type="checkbox" tabindex="2" />

How to

How to change the state programmatically

The checked attribute of the input checkbox element permits:

  • to test the state (if true, the checkbox is checked)
  • to set the state

Example

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";
  }
}
<form onSubmit="toggleCheckBox(event)">
<input type="checkbox" name="checkbox" checked="true" /></br>
<button type="submit" name="button">Uncheck the checkbox</button>
</form>
  • Result:

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

<form>
<fieldset name="clubfields" disabled>
 <legend> <label>
  <input type=checkbox name=club onchange="form.clubfields.disabled = !checked">
  Use Club Card
 </label> </legend>
 <p><label>Name on card: <input name=clubname required></label></p>
 <p><label>Card number: <input name=clubnum required pattern="[-0-9]+"></label></p>
 <p><label>Expiry date: <input name=clubexp type=month></label></p>
</fieldset>
</form>
  • Just click the checkbox to see it in action.

Aria Role

With aria role, you need to handle programmatically the state of each attribute as seen in this example 3)

The code:

  • The Css
[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 {
   border-color: black;
   background-color: #EEEEEE;
}
  • The Javascript:
window.onload=function() { 
    var checkboxes = document.querySelectorAll('[role="checkbox"]'); 
    for (var i = 0; i < checkboxes.length; i++) { 
         var cb = new Checkbox(checkboxes[i]); cb.init(); 
    } 
}
  • The HTML (tabindex makes the div focusable (ie clickable)
<div id="ex1">
  <h3>
    Sandwich Condiments
  </h3>
  <div>
    <div role="checkbox"
       aria-checked="false"
       tabindex="0">
      Lettuce
    </div>
    <div role="checkbox"
       aria-checked="true"
       tabindex="0">
      Tomato
    </div>
    <div role="checkbox"
       aria-checked="false"
       tabindex="0">
      Mustard
    </div>
    <div role="checkbox"
       aria-checked="false"
       tabindex="0">
      Sprouts
    </div>
  </div>
</div>

<!-- With the libray call at the end -->
<!-- Checkbox widget that implements ARIA Authoring Practices for a menu of links -->
<script src="https://www.w3.org/TR/wai-aria-practices/examples/checkbox/checkbox-1/js/checkbox.js" type="application/javascript"></script>

Documentation / Reference





Discover More
HTML - Checked

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...
HTML - Label

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 element....
HTML - Legend

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 ...
Html Radio Illustration
HTML - Radio

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...
Html Checkbox Illustration
How to create a checkbox in React?

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...
Formdata Browser Devtool
How to use FormData and send multipart-data in the Browser (Web API )?

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...
What are Form Control elements in HTML ?

control form elements are elements that are used specifically inside a form. They are used: to specify a key and a value. to layout the form to submit it or reset it field set [optional]...
What are HTML Input Elements?

An inputinput element of a form control that permits to define a scalar value (single value) inputFull list Ref Doc The type attribute defined: the default behavior the design of the element....



Share this page:
Follow us:
Task Runner