Skip to content
the poor coder

set a checkboks to defoult checked

Poor Man
Published
Reading time
1 min read
On this page

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:

Text

    <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:

Text

    <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:

Text

    <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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC