Reputation: 2006
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 select box value.
If I select the option RED the the value of the option Red(/static/imag1.jpg) should fill in the src of the image.
And also select the first option value as the default image.
Upvotes: 5
Views: 19902
Reputation: 8726
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());
}
Upvotes: 0
Reputation: 1592
You can set onchange
event to the 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
Upvotes: 1
Reputation: 15603
$(document).ready(function(){
$("#kitchen_color").change(function(){
$("img[name=image-swap]").attr("src",$(this).val());
});
});
Use above code.
Upvotes: 7
Reputation: 9947
use a change function on your select list
$('#kitchen_color').change( function() {
$("#imgid").attr("src","new src value");
});
Upvotes: 2