You can use the HTML input
tag to create a checkbox. The HTML input
tag displays a checkbox when you set the type
attribute with the value, "checkbox"
.
If you’ve been searching for what is the correct HTML for making a Checkbox, look no further. Let’s jump right into the details.
The syntax
The general syntax of HTML input
tag to display a checkbox is as follows -
<input type="checkbox" id="id" name="name" value="value" checked="Yes/No">
- The
type
attribute specifies the type of input control you need. - The
id
attribute specifies a unique id for the checkbox control. You can use this unique id to identify the control from your CSS or JavaScript source code. - The
name
attribute specifies a name for the HTML checkbox. You can use the name to identify a group of checkboxes from your CSS or JavaScript source code - The
value
attribute specifies the string value the checkbox represents. - The
checked
attribute is a boolean attribute. If you need to set it to true if you need to display the checkbox as checked by default. This attribute works only during page loads. It doesn’t reflect the current status of the HTML checkbox control.
A coding sample
Here comes a simple example that used HTML checkbox control
<!DOCTYPE html>
<html lang="en">
<head>
<title> A Sample Web Page </title>
</head>
<body>
<p> Choose your subject(s) -</p>
<input type="checkbox" id="Subject_1" name="Subject" value="Mathematics" checked="true">
<label for="vehicle1"> Mathematics</label><br>
<input type="checkbox" id="Subject_2" name="Subject" value="Physics">
<label for="vehicle2"> Physics</label><br>
<input type="checkbox" id="Subject_3" name="Subject" value="Chemistry">
<label for="vehicle3"> Chemistry</label><br><br>
<input type="submit" value="Submit">
</body>
</html>
In the above example, there exist three HTML checkbox controls. These three checkbox control corresponds to three different subjects.
All these HTML checkbox controls have unique ids and the same name. The HTML checkbox control for Mathematics stays checked by default.
Get my free e-book to prepare for the technical interview or start to Learn Full-Stack JavaScript