checkbox in HTML

Checkboxes are very useful in forms. They allow you to select a single entity while submitting the form.
Let us have a look at an example.


<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <input type="checkbox" id="sharpner" name="entity" value="sharpner" />
        <label for="sharpner">Sharpners</label>
    </body>
</html>
                        

Attributes

Following attributes can be used while using checkbox.

value attribute

value is assigned a string which will not be shown in browser but it will be sent to server with the name of the checkbox. The value will only be sent to the server if a checkbox is checked.
Let us have a look at example.


<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <form>
            <div>
                <input type="checkbox" id="subscribe" name="subscribe" value="newsletter">
                <label for="subscribe">Subscribe to newsletter?</label>
            </div>
            <div>
                <button type="submit">Submit</button>
            </div>
        </form>
    </body>
</html>
                        

In the above code, if a checkbox is checked, the data "subscribe=newsletter" will be sent to the server.
If value attribute is not present, then data "subscribe=on" will be sent to the server if a checkbox is checked.

checked attribute

checked attribute is presend if checkbox is checked.


<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <input type="checkbox" checked id="subscribe" />
        <label for="subscribe" style="font-weight:normal;">Subscribed?</label>
    </body>
</html>
                        

In above code, checked attribute is used to make checkbox by default checked.

for attribute

for attribute is not used in checkbox but in the attached label. Value of the for is the id of the checkbox. So that when we click on the label checkbox gets checked/unchecked. It increases the hit area of the checkbox.

Multiple Checkboxes

You can have multiple checkboxes with different name but what if you want to send the data with the same name so that data can be handled with a single variable.


<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <div>
            <input type="checkbox" id="sharpner" name="stationary[]" value="sharpner">
            <label for="sharpner">Sharpner</label>
        </div>
        <div>
            <input type="checkbox" id="eraser" name="stationary[]" value="eraser">
            <label for="eraser">Eraser</label>
        </div>
    </body>
</html>
                        

In the above code, when you submit the form, data like "stationary[]=sharpner&stationary[]=eraser" will be sent if both the checkboxes are checked.

Conclusion

In this section, we have learned about the checkbox.
In next section we will learn about radio buttons in HTML.