简体   繁体   中英

Jquery: dynamically change an img src based on dropdown selected value

I would like to dynamically display an image after the user has selected it. The different options are generated from a SQL query.

It works when I specify the image as a value:

<select id="SelectLogo" onchange="document.getElementById('logo').src='/images/'+this.value" >
   <option value="img1.png">Image 1</option>
   <option value="img2.png">Image 2</option>
   <option value="img3.png">Image 3</option>
</select>
<img id="logo" src="">

But now I need to post an Id but not the image name. I have tried that:

 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select id="SelectLogo" onchange="document.getElementById('logo').src='/images/'+$(this).attr('data-img')" > <option value="1" data-img="img1.png">Image 1</option> <option value="2" data-img="img2.png">Image 2</option> <option value="3" data-img="img3.png">Image 3</option> </select> <img id="logo" src="">

I got an error: undefined

You can use $(this).find('option:selected').data('img') to get the selected option data-attribute.

Demo Code :

 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select id="SelectLogo" onchange="document.getElementById('logo').src='/images/'+$(this).find('option:selected').data('img')" > <option value="1" data-img="img1.png">Image 1</option> <option value="2" data-img="img2.png">Image 2</option> <option value="3" data-img="img3.png">Image 3</option> </select> <img id="logo" src="">

Also you can use jquery change event handler instead of javascript onchange attribute. Using this way you can fire change event on page load and set image src in page load.

$("#SelectLogo").change(function(){
  $("#logo").attr("src", '/images/'+$(":selected", this).data('img'));
}).change();

 $("#SelectLogo").change(function(){ $("#logo").attr("src", '/images/'+$(":selected", this).data('img')); console.log($("#logo").attr("src")); }).change();
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select id="SelectLogo"> <option value="1" data-img="img1.png">Image 1</option> <option value="2" data-img="img2.png">Image 2</option> <option value="3" data-img="img3.png">Image 3</option> </select> <img id="logo" src="">

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