How to Create A Read-Only Checkbox in HTML

Naila Saad Siddiqui Feb 15, 2024
  1. Overview of HTML Checkbox
  2. Read-Only Checkbox in HTML
How to Create A Read-Only Checkbox in HTML

This article is a quick hack on how we can make an HTML checkbox control a read-only component. But, first, let’s have a brief introduction to checkbox control.

Overview of HTML Checkbox

The default rendering of <input> elements of the type checkbox is a box that is checked (tick marked) when activated, similar to what you might see on a legitimate government paper form.

The operating system setup that the browser is using determines the exact appearance. For example, it is typically square but could have rounded corners. Also, unlike radio buttons, you can select more than one option in the checkboxes.

Syntax:

<input type="checkbox" id="physics" name="physics" checked>
      <label for="physics">Physics</label>
<input type="checkbox" id="maths" name="maths">
      <label for="maths">Mathematics</label>
<input type="checkbox" id="cs" name="cs">
      <label for="cs">Computer Science</label>

It is to be noted that the checkbox name is not its display name. The display name is specified through the <label> tag. This name is used on the server side when the form is submitted.

When the form is submitted, we get the value of only checked checkboxes. It is because a disabled or unchecked box’s value is not received on the server side.

Read-Only Checkbox in HTML

Suppose you have a case where you need to forcefully check the checkbox and not allow the user to uncheck it or make it a read-only field; we can achieve this through a JavaScript function.

<HTML>
    <head>
    <script>
        function makeReadOnly() {
            return false;
        }
    </script>
    <body>
       <input type="checkbox" id="physics" name="physics" onClick="return makeReadOnly()" checked>
       <label for="physics">Physics</label> <br/>
       <input type="checkbox" id="maths" name="maths" disabled>
       <label for="maths">Mathematics</label><br/>
    </body>
</html>

In this HTML code, we made two checkboxes; one is made read-only, and the other is made disabled. For making a checkbox read-only, we return false when the user clicks it.

It will make the state of the checkbox unchanged as it is already checked, so it will remain checked, regardless of the user clicks.

When the form is submitted, this checked checkbox’s value will be sent with the form data, whereas it will not send the disabled checkbox’s data. Let us look at the output:

read only checkbox in html - output two

Note that the disabled checkbox is greyed out, and the user will not be able to check or uncheck it.

Related Article - HTML Checkbox