Home > Software engineering >  I am trying to display an image once a checkbox is checked but the code is not working
I am trying to display an image once a checkbox is checked but the code is not working

Time:01-10

Here is my code:

        <form>
            White
            <input id="white" type="checkbox" onclick="checkMe()"/>
            <img id="www" style="display: none;" src="assets/2.jfif" alt="shirt">
        </form>
        <script>
        function checkMe(){
            var cb = document.getElementById("white");
            var img = document.getElementById("www");
            if(cb.checked==true){
                text.style.display="block";
            } else {
                text.style.display="none";
            }
        }
        </script>

The checkbox is indicating that it is being checked but the image is not displaying. Ive tried possible solutions but none have helped. Any insights will be appreciated.

CodePudding user response:

Found the solution.

 text.style.display="block";
text.style.display="none";

Replace text with img

CodePudding user response:

var cb = document.getElementById("white");
var img = document.getElementById("www");

function checkMe() {

  if (cb.checked == true) {
    img.style.display = "block";
  } else {
    img.style.display = "none";
  }

}
<input id="white" type="checkbox" onclick="checkMe()" />
<img id="www" style="display: none;" src="https://sample-videos.com/img/Sample-png-image-100kb.png" alt="shirt">

Simple Method - without Js

img {
  display: none
}

input {
  height: 30px;
  width: 30px;
}

input:checked  img {
  display: block
}
<input type="checkbox" />
<img src="https://sample-videos.com/img/Sample-png-image-100kb.png" >

CodePudding user response:

You Just need to Replace the wrong selector with your image selector variable into the JavaScript function.

Below Is the function I'm sharing with you. You should replace this function with the old one.

function checkMe() {
    var cb = document.getElementById("white");
    var img = document.getElementById("www");
    if (cb.checked == true) {
        img.style.display = "block";
    } else {
        img.style.display = "none";
    }
}
  • Related