简体   繁体   中英

How do I set an image to display from a dropdown menu option?

I'm trying to make a form that displays a movie poster when you select which movie you'd like to see. I wrote a function but I'm new to javascript and something isn't working correctly.

Thanks for any help provided.

JS

function setMovie() {
  var img = document.getElementById("movimg");
  var value = img.options[img.selectedIndex].value;
  var selected = document.getElementById("selectedMovie");
  selected.src = this.value;
  return false;
}
document.getElementById("movieList").onChange = setMovie();

HTML

<select id="movimg" onChange="setMovie(this)">
  <option value="null.png">Select a movie!</option>
  <option value="bvs.jpg">Batman vs. Superman</option>
  <option value="tjb.jpg">The Jungle Book</option>
  <option value="tgf.jpg">The Godfather</option>
  <option value="tpb.jpg">The Princess Bride</option>
  <br>
</select>
<img src="" id="selectedMovie" />

You were referencing movieList , an id that wasn't there. You also did not need to return false in your function.

 var select_box = document.getElementById("movimg"), image_box = document.getElementById("selectedMovie"); function setMovie() { var value = select_box.options[select_box.selectedIndex].value; image_box.src = this.value; } select_box.addEventListener("change", setMovie); 
 <select id="movimg"> <option value="null.png">Select a movie!</option> <option value="bvs.jpg">Batman vs. Superman</option> <option value="tjb.jpg">The Jungle Book</option> <option value="tgf.jpg">The Godfather</option> <option value="tpb.jpg">The Princess Bride</option> </select> <img src="" id="selectedMovie"/> 

You can just change your function to this:

 function setMovie(){
    document.getElementById("selectedMovie").src = document.getElementById("movimg").value;
    }

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