An HTML Checkbox as the name suggests contains a small box which can be checked or unchecked.
Let us understand HTML checkbox with the following example. Say your Mother has asked you to go the market and get the list the fruits :
Apple Mango Guava
So, you go to the market and collect the apple and put a tick in Apple.
✓ Apple Mango Guava
Then collect Mango and put a tick in Mango.
✓ Apple ✓ Mango Guava
So, don't you think, if there could be a way in HTML where we can put a tick just the way we have done above.
And luckily with HTML Checkbox we can achieve the same.
Checkbox is a small square box in HTML that can be selected with a tick. There can be a number of checkboxes in a group and user can select a checkbox based on their needs.
We can create a Checkbox in HTML using the type attribute of the <input> tag.
Let us understand Checkbox with the below example.
<html> <body> <form> <input type="checkbox" id="apple" name="apple" value="Apple"> <label for="apple"> Apple </label><br> <input type="checkbox" id="mango" name="mango" value="Mango"> <label for="mango"> Mango </label><br> <input type="checkbox" id="guava" name="guava" value="Guava"> <label for="guava"> Guava</label> </form> </body> </html>
So, if you look at the above output, there are three checkboxes for Apple, Mango and Guava. And you can check and uncheck the checkboxes.
Now, let us come to the code. In the above code we have used the <input> tag and set the value of type attribute as checkbox.
<input type="checkbox" id="apple" name="apple" value="Apple">
And we have the checkbox ready for the value Apple.
Our next task is to create a label for the above checkbox. And for that we have used the <label> tag.
<label for="apple"> Apple </label><br>
The <label> tag creates a label named Apple.
And in the same way the other checkboxes are created.
<input type="checkbox" id="mango" name="mango" value="Mango"> <label for="mango"> Mango </label><br> <input type="checkbox" id="guava" name="guava" value="Guava"> <label for="guava"> Guava</label>
In the above example we have created a checkbox that was unchecked(i.e. There was no tick on the checkbox).
Now, let us see, how can we create a checkbox that is already checked(i.e. There would be a tick mark on the checkbox).
<html> <body> <form> <input type="checkbox" id="apple" name="apple" value="Apple" checked="yes"> <label for="apple"> Apple </label><br> </form> </body> </html>
So, in the above code all we have done is, used the checked attribute of the <input> tag. And set the value of checked attribute to yes.
<input type="checkbox" id="apple" name="apple" value="Apple" checked="yes">