set a checkboks to defoult checked

Setting a Checkbox to Default Checked

Setting a checkbox to default checked can be useful in situations where you want to pre-select an option for the user so they don't have to manually select it. Here are a few ways to achieve this:

Using the Checked Attribute

The easiest way to set a checkbox to default checked is by adding the "checked" attribute to the input tag. Here's an example:


    <input type="checkbox" name="example" value="1" checked> Example Checkbox

In the above code, the "checked" attribute is added to the input tag, which will automatically check the checkbox by default when the page loads.

Using JavaScript

If you need to dynamically set a checkbox to default checked based on some condition, you can use JavaScript to achieve this. Here's an example:


    <input type="checkbox" name="example" value="1" id="example"> Example Checkbox

    <script>
        document.getElementById("example").checked = true;
    </script>

In the above code, we give our checkbox an ID of "example" and then use JavaScript to set its "checked" property to true, which will check it by default when the page loads.

Using CSS

While not technically setting a checkbox to default checked, you can use CSS to visually style a checkbox as if it is checked. Here's an example:


    <style>
        input[type="checkbox"][name="example"]:checked + label:before {
            content: "\2713";
            font-size: 16px;
        }
    </style>

    <input type="checkbox" name="example" id="example">
    <label for="example">Example Checkbox</label>

In the above code, we use CSS to target the "checked" state of our checkbox and add a checkmark symbol before the label text. While the checkbox itself isn't technically checked, it appears as if it is to the user.

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