3.0.0-alpha.7 Alpha
Default Default Classic Light Dark Light Dark System
Search /
Default Default Classic Light Dark Light Dark System
Native Styles

Checkbox

Checkboxes allow the user to toggle an option on or off.

Want to do more? Check out the <wa-checkbox> component!
<label><input type="checkbox"> Checkbox</label>

Examples

Checked

Use the checked attribute to activate the checkbox.

<label><input type="checkbox" checked> Checked</label>

Disabled

Use the disabled attribute to disable the checkbox.

<label><input type="checkbox" disabled> Disabled</label>

Custom Validity

Use the setCustomValidity() method to set a custom validation message. This will prevent the form from submitting and make the browser display the error message you provide. To clear the error, call this function with an empty string.


<form class="custom-validity">
  <label><input type="checkbox"> Check me</label>
  <br />
  <button type="submit" variant="brand" style="margin-top: 1rem;">Submit</button>
</form>
<script>
  const form = document.querySelector('.custom-validity');
  const checkbox = form.querySelector('input[type=checkbox]');
  const errorMessage = `Don't forget to check me!`;

  // Set initial validity
  checkbox.setCustomValidity(errorMessage);

  // Update validity on change
  checkbox.addEventListener('change', () => {
    checkbox.setCustomValidity(checkbox.checked ? '' : errorMessage);
  });

  // Handle submit
  form.addEventListener('submit', event => {
    event.preventDefault();
    alert('All fields are valid!');
  });
</script>
    No results