Home > Enterprise >  Problem with image changing function in JS
Problem with image changing function in JS

Time:04-22

the problem is resolved, it was an issue with the browser, thanks for your help

I have an HTML\JS\CSS school project, in this page, I wanted to make a function who changes the the image appearing. but it appears that there is a problem in the program, could anyone help me to know what is the problem exactly

function changeImage(img) {
  path = img.options[img.selectedIndex].value;
  document.getElementById('image').src = path;
}
<select onchange="changeImage(this)">
  <option value="image3.png" selected>image3</option>
  <option value="image2.png">Boston image2</option>
  <option value="image1.png">Brooklyn image1</option>
</select>
<img src="image1.png" id="image">

CodePudding user response:

You can provide support for all browsers with this code:

function changeImage(img) {
  path = img.value || img.options[target.selectedIndex].value;
  document.getElementById('image').src = path;
}

CodePudding user response:

set image on initial load to first option

function changeImage(img) {
  path = img.options[img.selectedIndex].value;  
  document.getElementById('image').src = path;
}
<select onchange="changeImage(this)">
  <option value="https://via.placeholder.com/50" selected>image3</option>
  <option value="https://via.placeholder.com/75">Boston image2</option>
  <option value="https://via.placeholder.com/100">Brooklyn image1</option>
</select>
<img src="https://via.placeholder.com/50" id="image">

CodePudding user response:

<select onchange="changeImage()">
    <option value="select option" selected>Select Option</option>
    <option value="image3.png" id="image3">image3</option>
    <option value="image2.png" id="image2">image2</option>
    <option value="image1.png" id="image1">image1</option>
  </select>
  <!-- Img Show Will Be Here -->
  <img id="img">

<script>
      function changeImage() {
          if(document.getElementById("image3").selected == true) {
              document.getElementById("img").src = "your image"
          }

          if(document.getElementById("image2").selected == true) {
              document.getElementById("img").src = "your image";
          }
          if(document.getElementById("image1").selected == true) {
              document.getElementById("img").src = "your image"
          }
      }
  </script>

  • Related