Checkbox in HTML is used as a form element to let users select one or more options from a bunch of choices. It is displayed as a square element that can be checked to select the appropriate option. In this article, we will see how to create a checkbox in HTML.
What is the correct HTML for making a checkbox?
The correct HTML to create a checkbox is very simple. To make a checkbox you need to use
input tag with
type="checkbox" attribute. It’s all that is required by HTML specification.
How to add value to the checkbox?
To add value to the checkbox you need to add
value attribute with the value you want to set between quotation marks. Default value for the checkbox is “on” when checkbox is checked and “off” when checkbox is unchecked.
<input type="checkbox" value="Dog">
How to pass checkbox value when the form is submitted?
To pass checkbox value with the data, when the form is submitted, you need to add
name attribute which is used as an identifier of the specific checkbox. Without this attribute, the checkbox field is correct but useless.
<input type="checkbox" name="animal" value="Dog">
How to add label together with the checkbox?
Without an appropriate label, checkbox can be unreadable to the user. To fix this you can add
label and connect both tags together with the
<label for="question">What animal do you have?</label> <input type="checkbox" name="animal" value="Dog" id="question">