HTML Form with Checkboxes examples and sample code

Checkboxes can be used in different cases:

  1. You can use a single checkbox to make the user turn on or off an option (just like a switch). For example:

    Do you want to opt-in for our newsletter?

  2. You can provide a number of checkboxes where the user can choose more than one options Choose your favourite colors:

    Red

    Green

    Blue

Checkbox form element is created by specifying type=checkbox attribute in <input> tag. It creates a checkbox on the form, which has only two values; on or off. By default, the state of the checkbox form element is off (blank) but when you use checked attribute in <input> tag then it becomes selected by default.

# Single Checkbox (on/off type)

Note that the second option uses the value attribute. Press the submit button to see the value that gets submitted when you check and uncheck the options

# Multiple Checkboxes (choose any number of options)

When you want to allow more than one option to be selected from a group of options, a group of checkboxes is the best choice.

To see this working, select more than one option below and press the submit button. Then see the results in the console window.