Search code examples
javascriptjqueryhtml-selectsrcsrcset

Changing the SRC of an image depending on the selected option


I have to change the atribute "src" of multiple images with different items.

So I'm trying to do it with this code:

script

function ColorSrcSet(ImageId) {
  var imgID = document.getElementById(ImageId);
  var optionValue = $(this).attr("value");
  imgID.src = optionValue;
}

html

  <select onchange="ColorSrcSet('img-1');">
    <option value="../img/1.png">Amarillo</option>
    <option value="../img/2.png">Naranja</option>
    <option value="../img/3.png"></option>
  </select>

  <img id="img-1" src="../img/transparent.png"></img>

It gives me an error and set the "SRC" as undefined.

¿Do anyone know how to fix it?


Solution

  • There is no explicit this in an onchange function

    You can pass the value as another argument though

    JS

    function ColorSrcSet(ImageId, selectVal) {
       document.getElementById(ImageId).src = selectVal;     
    }
    

    HTML

    <select onchange="ColorSrcSet('img-1', this.value);">