HomeLinuxTips on how to Make Checkbox Readonly in JavaScript

Tips on how to Make Checkbox Readonly in JavaScript


A checkbox corresponds to a sq. field that’s marked/checked when the person clicks on it. It permits the customers to pick out one or a couple of possibility from the variety of decisions. It’s usually used within the varieties for affirmation and validation. By default, it’s deactivated i.e., an empty sq. field. Nonetheless, the person can activate it dynamically on the entrance finish. Additionally, its performance may also be disabled or deactivated to make it read-only.

This information illustrates the method to creating a checkbox read-only utilizing JavaScript.

Tips on how to Make Checkbox Readonly in JavaScript?

The DOM enter checkbox “disabled” property helps to set and discover out whether or not the actual checkbox factor is enabled or disabled. This property by default returns “false” i.e., if a checkbox will not be disabled, and “true” for disabled. On this part, it’s utilized to make the given checkbox read-only.

HTML Code

First, take a look at the given HTML code:

Checkbox: <enter sort=“checkbox” id=“field1” checked=true>

<button onclick=“readOnly()”>Make Readonly</button>

Within the above code block:

  • The “<enter>” tag provides a “checkbox” with the assistance of the enter sort “checkbox”, id “field1” and the “checked” property’s standing as “true”.
  • Subsequent, the “<button>” tag embeds a button to execute the “readOnly()” perform when its related “onclick” occasion is fired.

JavaScript Code

Subsequent, an outline of the JavaScript code:

<script>

perform readOnly() {

var checkbox = doc.getElementById(‘field1’);

checkbox.disabled = true;

}

</script>

Within the above code snippet:

  • Outline a perform named “readOnly()”.
  • In its definition, the “checkbox” variable applies the “getElementById()” methodology to entry the given checkbox utilizing its id “field1”.
  • Lastly, set the standing of the “disabled” property by specifying its worth “true” which disables the accessed checkbox.

Output

Tips on how to Make Checkbox Readonly in JavaScript

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

Conclusion

To make the checkbox read-only, use the JavaScript “disabled” property by specifying its standing as “true”. This property converts the focused checkbox into “gray” which signifies that it’s “disabled” and the person can solely learn it, not verify or uncheck. This information briefly illustrated the method to creating a checkbox read-only in JavaScript.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments