Jenny Prs
Jenny Prs

Reputation: 43

Change image with select-option value JS

Can someone tell me how to change the image with JS when the user selects different option?

For example for purple color the image source is images/purple.jpg

<select id="guitar-color">
  <option value="normal" id="normal-color">Normal</option>
  <option value="purple" id="purple-color">Purple</option>
  <option value="black" id="black-color">Black</option>
  <option value="red" id="red-color">Red</option>
  <option value="blue" id="blue-color">Blue</option>
</select>
<img src="images/normal.jpg" id="img-color">

Upvotes: 1

Views: 1917

Answers (2)

cMarius
cMarius

Reputation: 1132

Something like this perhaps (the image will appear broken, but if you inspect the code, it changes the url):

function changeImage(element) {
  document.querySelector("#img-color").src = "images/" + element.value + ".jpg"
}
<select id="guitar-color" onChange="changeImage(this);">
  <option value="normal" id="normal-color">Normal</option>
  <option value="purple" id="purple-color">Purple</option>
  <option value="black" id="black-color">Black</option>
  <option value="red" id="red-color">Red</option>
  <option value="blue" id="blue-color">Blue</option>
</select>
<img src="images/normal.jpg" id="img-color">

Upvotes: 2

Hassen Ch.
Hassen Ch.

Reputation: 1763

You can get inspired by this. Just add the list of images and change them according to what you want.

var pictureList = [
  "https://as1.ftcdn.net/jpg/00/89/85/08/500_F_89850844_YGSGp8OPRTpJsNyKOuQN1Fsl1zUlQpeo.jpg",
  "https://as1.ftcdn.net/jpg/00/89/80/90/500_F_89809058_N0zsAk9QNaMrLzfaL00W0cwtDsCs8HLL.jpg",
  "https://as1.ftcdn.net/jpg/00/89/85/08/500_F_89850856_B2T5QVSvqyap1cUE34Of2Z6zXbMrkDQm.jpg"
];

$('#picDD').change(function() {
  var val = parseInt($('#picDD').val());
  $('img').attr("src", pictureList[val]);
});
img {
  width: 400px;
  margin: auto;
}

#picDD {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="picDD">
  <option value="0" selected>Picture 1</option>
  <option value="1">Picture 2</option>
  <option value="2">Picture 3</option>
</select>
<img src="https://as1.ftcdn.net/jpg/00/89/85/08/500_F_89850844_YGSGp8OPRTpJsNyKOuQN1Fsl1zUlQpeo.jpg" />

Upvotes: 2

Related Questions