Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I change the color of my card when I click mycheckbox?

I want to use JS to change the color of my card when I click the checkbox. My current issue is that I’m not sure how to reference these elements in JS.

<body>
    <div class="container">
        <div class ="card">
            <input type="checkbox" name="platform" value="ana" id="ana">
            <label for="ana">
                <div class="card-image">
                    <img src="./images/Ana.png" alt="Character">
                </div>

                <div class="card-body">
                    <img class="heroCardRole" src="./images/Support.svg">
                    <h2>Ana</h2>
                    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Error laudantium sequi facere mollitia saepe.</p>
                </div>
                    
            </label>
        </div>
</body>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

To see changes in the checkbox state we can add an onClick event such as:

<input type="checkbox" onclick="validate()" name="platform" value="ana" id="ana">

With this code, any time there is a change to the checkbox, we run the validate function.

To target the card in particular, we add id="card" to it and then we can use document.getElementById('ana') to reference it and change its color.

<div class ="card" id="card">

Then, anytime the checkbox changes status to checked, we just add the class containing the background color we want to the card. When it is unchecked, we remove the class we added.

       function validate() {
            if (document.getElementById('ana').checked) {
                document.getElementById('card').classList.add("red")
            } else {
                document.getElementById('card').classList.remove("red")
            }
        }
.red {background: red}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading