David David - 1 month ago 6
HTML Question

Show image depending on select option with custom value attribute

What I want to reach:

Show an image depending on select box selection. But I don't want to take attribute

value=""
, I want to take a custom attribute
data-img=""
instead.

This is the code I actually have, but it's not working:

<html>
<head>
<script src="http://code.jquery.com/jquery-latest.pack.js"></script>
<script>
function showFormatImage() {
var image = document.getElementById("itemImage");
image.src = $('select[name=itemImage] option:selected').data('img');
return false;
}
document.getElementById("itemImage").onchange = showFormatImage;
</script>
</head>
<body>

<select id="itemImage" name="itemImage">
<option data-img="first.png">First</option>
<option data-img="second.png">Second</option>
<option data-img="third.png">Third</option>
</select><br>

<img id="itemImage" src="">

</body>
</html>


No image is shown. Does anybody know what's wrong?

P.S.: If there's a non-Javascript solution, that would be even better but I don't think there is.

Answer
var image = document.getElementById("itemImage");

var image is the select - not the img, also - itemImage does not exist at time of execution so the event handler isn't placed.

you should change your code to:

<html>
    <head>
         <script>
          window.onload = function() {
              document.getElementById("itemImage").onchange = showFormatImage;
           };
          function showFormatImage() {
             var image = document.getElementById("changeImage");
             image.src = $('select[name=itemImage] option:selected').attr('data-img');
             return false;
          }

         </script>
     </head>
     <body>

       <select id="itemImage" name="itemImage">
             <option data-img="first.png">First</option>
             <option data-img="second.png">Second</option>
             <option data-img="third.png">Third</option>
       </select><br>

         <img src="" id='changeImage'/>
    </body>
</html>

jquery solution:

 $(document).ready(function(){
     $('#itemImage').change(function(){
         var src = $(this).find('option:selected').attr('data-img');
         $('img#changeImage').attr('src',src);
     });
});
Comments