简体   繁体   中英

HTML - selectedindexchanged of dropdown not working for the second time

Below is the code where the image should be displayed on changing the value of the dropdownlist --

<html>
 <head><title>Image Display</title></head>
   <script type = "text/JavaScript">
        function displayImage() {
        var dropdown1 = document.getElementById('dropdown1');
        var index = dropdown1.options[dropdown1.selectedIndex].value;
    //alert(index);

    var img = new Image();  
    if(index == 0){
        img.src = "D:\\Images\\LamborghiniLaunche.png"
        imgDiv.appendChild(img);
    }   
    else if(index == 1){
        img.src = "D:\\Images\\Nano.JPG"
        imgDiv.appendChild(img);
    }
    else if(index == 2){
        img.src = "D:\\Images\\bmw-i8.jpg"
        imgDiv.appendChild(img);
     }
  }
  </script>
  <body>
<select id="dropdown1" name ="select" onchange="displayImage();">
    <option selected disabled>Select here</option>
    <option value ="0">Lamborghini Launche
    <option value ="1">Nano
    <option value ="2">BMW i8
    </option>
    </select>

<div id="imgDiv"></div>
</body>
</html>

Problem: After selecting the dropdown value for the first time, it loads the corresponding image successfully but changing the drop-down value for the second time fails to loads the corresponding image.

You probably don't want to create and addend new images on every option change. It may be that due to your styles you simply don't see new image, because it's after the first one.

Instead create image if it doesn't exist and change its src if it's already there. Something like this:

 function displayImage() { var dropdown1 = document.getElementById('dropdown1'); var index = dropdown1.options[dropdown1.selectedIndex].value; var imgDiv = document.querySelector('#imgDiv img'); if (!imgDiv) { imgDiv = new Image(); document.querySelector('#imgDiv').appendChild(imgDiv); } if (index == 0) { imgDiv.src = "http://lorempixel.com/100/100/food/1"; } else if (index == 1) { imgDiv.src = "http://lorempixel.com/100/100/food/2" } else if (index == 2) { imgDiv.src = "http://lorempixel.com/100/100/food/3"; } } 
 <select id="dropdown1" name="select" onchange="displayImage();"> <option selected disabled>Select here</option> <option value="0">Lamborghini Launche</option> <option value="1">Nano</option> <option value="2">BMW i8</option> </select> <div id="imgDiv"></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM