set default value checkbox javascript

Setting Default Value for a Checkbox using Javascript

Introduction

A checkbox is an important element in HTML forms that allows users to select one or multiple options. By default, a checkbox element is unchecked. However, there are cases where we may want to set a default value for the checkbox based on certain conditions. This can be achieved using Javascript.

Method 1: Using the checked Attribute

One way to set a default value for a checkbox is by using the checked attribute. The checked attribute is a boolean attribute that specifies whether a checkbox should be checked or not. To set a default value for a checkbox, we can use Javascript to add the checked attribute to the input element.


// Get the checkbox element
var checkbox = document.getElementById("myCheckbox");

// Set the default value
checkbox.checked = true;

In the above code, we first get the checkbox element using its ID. We then set the checked attribute to true, which will check the checkbox by default.

Method 2: Using the value Attribute

Another way to set a default value for a checkbox is by using the value attribute. The value attribute specifies the value that will be submitted when the checkbox is checked. By default, the value of a checkbox is "on". However, we can change this value using Javascript.


// Get the checkbox element
var checkbox = document.getElementById("myCheckbox");

// Set the default value
checkbox.value = "yes";

In the above code, we first get the checkbox element using its ID. We then set the value attribute to "yes", which will be submitted when the checkbox is checked by default.

Conclusion

Setting a default value for a checkbox is a simple task that can be achieved using Javascript. We can either use the checked attribute to check the checkbox by default, or use the value attribute to specify a default value that will be submitted when the checkbox is checked. By using these methods, we can create more user-friendly forms that will enhance the user experience.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe