Change the src value of the image based on the parameter value in the selection box

I have an img tag and a select box

<img src="" name="image-swap"> <select name="kitchen_color" id="kitchen_color"> <option value="/static/imag1.jpg">Red</option> <option value="/static/imag2.jpg">Black</option> <option value="/static/imag3.jpg">White</option> </select> 

I need to change the src value of the img tag based on the value of the select box.

If I select the RED option, the value of the Red option (/static/imag1.jpg) should fill in the src of the image.

And also select the first parameter value as the default image.

+4
source share
4 answers
 $(document).ready(function(){ $("#kitchen_color").change(function(){ $("img[name=image-swap]").attr("src",$(this).val()); }); }); 

Use the code above.

+5
source

use the change function in the selection list

 $('#kitchen_color').change( function() { $("#imgid").attr("src","new src value"); }); 
+2
source

You can set the onchange event to select .

 <select name="kitchen_color" id="kitchen_color" onchange="setImage(this);"> <option value="https://www.google.ru/images/srpr/logo4w.png">Google</option> <option value="http://yandex.st/www/1.645/yaru/i/logo.png">Yandex</option> <option value="http://limg.imgsmail.ru/s/images/logo/logo.v2.png">Mail</option> </select><br /> <img src="" name="image-swap" /> 

Javascript:

 function setImage(select){ var image = document.getElementsByName("image-swap")[0]; image.src = select.options[select.selectedIndex].value; } 

Example there

+1
source
 try this <img src="" class="image-swap"> <select name="kitchen_color" id="kitchen_color" onchange="change_image()"> <option value="/static/imag1.jpg">Red</option> <option value="/static/imag2.jpg">Black</option> <option value="/static/imag3.jpg">White</option> </select> $(document).ready(function(){ $('.image-swap').attr("src",$('#kitchen_color').val()); }) function change_image(){ $('.image-swap').attr("src",$('#kitchen_color').val()); } 
0
source

Source: https://habr.com/ru/post/1495285/


All Articles