Skip to content
Advertisement

Adding placeholder photo for dropdown menu select

I am trying to add a placeholder image in the paragraph tag. The users select an option and the photo is replaced by the one chosen. I have tried to add a photo as a valued on the first option but didn’t work. Any ideas please?

select { outline: none; width: 100%; padding: 10px 0; text-align: center;}
<select onchange="document.getElementById('preview2').src = this.value">
  <option selected="selected" disabled="disabled">Select a finish</option>
  <option value="/images/image1.jpeg">Chrome</option>
  <option value="/images/image2.jpeg">Satin Chrome</option>
  <option value="/images/image3.jpeg">Black</option>
  <option value="/images/image5.jpeg" ">Brushed Brass</option>
<option value="/images/image6.jpeg "">Brushed Nickel</option>
  <option value="/images/image7.jpeg" ">Powdercoated Gun Metal</option>
<option value="/images/image8.jpeg "">Gun Metal</option>
  <option value="/images/image9.jpeg" ">Antique Brass</option>
<option value="/images/image10.jpeg "">Black Chrome</option>
</select><br />
<p><img id="preview2" alt="" /></p>

Advertisement

Answer

Just trigger the change and have the default on the first option:

window.addEventListener("DOMContentLoaded", () => {  // when the page haas loaded
  const sel = document.getElementById("imgSel");
  const img = document.getElementById('preview2');
  const changeImg = () => { // called when image needs to be changed
    img.src = sel.value;
    img.title = sel.value;
    console.log(img.src); // for debugging
  };
  sel.addEventListener("change", changeImg); // better than inline event handler
  changeImg(); // initialise

})
#imgSel {
  outline: none;
  width: 100%;
  padding: 10px 0;
  text-align: center;
}

img {
  height: 100px;
  width: 100px;
  border: 1px solid black;
}
<select id="imgSel">
  <option selected="selected" disabled="disabled" value="/images/default.jpg">Select a finish</option>
  <option value="/images/image1.jpeg">Chrome</option>
  <option value="/images/image2.jpeg">Satin Chrome</option>
  <option value="/images/image3.jpeg">Black</option>
  <option value="/images/image5.jpeg">Brushed Brass</option>
  <option value="/images/image6.jpeg">Brushed Nickel</option>
  <option value="/images/image7.jpeg">Powdercoated Gun Metal</option>
  <option value="/images/image8.jpeg">Gun Metal</option>
  <option value="/images/image9.jpeg">Antique Brass</option>
  <option value="/images/image10.jpeg">Black Chrome</option>
</select><br />
<p><img id="preview2" alt="" /></p>
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement