JavaScript

How to Make Checkbox Readonly in JavaScript

A checkbox corresponds to a square box that is marked/checked when the user clicks on it. It allows the users to select one or more than one option from the number of choices. It is generally used in the forms for confirmation and validation. By default, it is deactivated i.e., an empty square box. However, the user can activate it dynamically at the front end. Also, its functionality can also be disabled or deactivated to make it read-only.

This guide illustrates the approach to making a checkbox read-only using JavaScript.

How to Make Checkbox Readonly in JavaScript?

The DOM input checkbox “disabled” property helps to set and find out whether the particular checkbox element is enabled or disabled. This property by default returns “false” i.e., if a checkbox is not disabled, and “true” for disabled. In this section, it is utilized to make the given checkbox read-only.

HTML Code

First, look at the given HTML code:

Checkbox: <input type="checkbox" id="field1" checked=true>

<button onclick="readOnly()">Make Readonly</button>

In the above code block:

  • The “<input>” tag adds a “checkbox” with the help of the input type “checkbox”, id “field1” and the “checked” property’s status as “true”.
  • Next, the “<button>” tag embeds a button to execute the “readOnly()” function when its associated “onclick” event is fired.

JavaScript Code

Next, an overview of the JavaScript code:

<script>

function readOnly() {

var checkbox = document.getElementById('field1');

checkbox.disabled = true;

}

</script>

In the above code snippet:

  • Define a function named “readOnly()”.
  • In its definition, the “checkbox” variable applies the “getElementById()” method to access the given checkbox using its id “field1”.
  • Lastly, set the status of the “disabled” property by specifying its value “true” which disables the accessed checkbox.

Output

As seen, the created checkbox (checked) disables upon the button click i.e., transformed to “read-only”.

Conclusion

To make the checkbox read-only, use the JavaScript “disabled” property by specifying its status as “true”. This property converts the targeted checkbox into “grey” which indicates that it is “disabled” and the user can only read it, not check or uncheck. This guide briefly illustrated the approach to making a checkbox read-only in JavaScript.

About the author

Areej Nadeem

I am a technical author holding a Bachelor’s degree in Computer Science. I am passionate about writing and learning new technologies and sharing my knowledge with the rest of the world.