How to add a checkbox in HTML

problem

You wish to add a checkbox on your webpage like shown below. In this post we will see an example of adding a checkbox and a group of checkboxes.

SOLUTION

Using the <input> tag with attribute type=”checkbox”. For example:

checkbox.html
				
					<input type="checkbox" />
				
			
output
checkbox example in HTML

After you click on it

checkbox example checked after clicked in HTML

Cool, let’s make it more user friendly by adding a description/ label next to it.

adding a label
checkbox.html
				
					<label for="coder">Are you a coder?</label>
<input type="checkbox" id="coder"/>
				
			
output

The label appears before the checkbox as we can see in the screenshot below:

checkbox with label example in HTML

If we wanted to show the checkbox first followed by the label, simply we can swap the line in out HTML file as follows:

checkbox.html
				
					<input type="checkbox" id="coder"/>
<label for="coder">Are you a coder?</label>
				
			
output

The HTML code is parsed line by line; meaning order matters.

checkbox with label after it in HTML
Check it by default

If we wish, we can have the checkbox ticked/ checked when the page loads. This can be done by simply using the attribute checked. For example:

checkbox.html
				
					<input type="checkbox" id="coder" name="options" checked/>
<label for="coder">Are you a coder?</label>

				
			
output
checkbox checked by default example in HTML

The checkbox is checked by default.

Disable the checkbox

We can make the checkbox disabled if we wish; meaning the user can’t click on it. To do that, we can simply put the attribute disabled, for example:

checkbox.html
				
					<input type="checkbox" id="coder" name="options" checked disabled />
<label for="coder">Are you a coder?</label>
				
			
output
checkbox disabled and checked example in HTML

Combining both attributes checked and disabled.

checkbox disabled and checked example in HTML

If we remove the attribute checked but keep the disabled attribute, the box looks grayed out and unclickable.

conclusion

In this post we saw how to use a checkbox on a web page and add attributes like id, name, checked and disabled to change its status and behaviour. 

 

References

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox

Share it!

Facebook
Twitter
LinkedIn
Reddit
Picture of Ellion

Ellion

Professional IT consultant, writer, programmer enthusiast interested in all sorts of coding.
Eats all cookies 🍪

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x