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.
To change the source or src of an image, you need to add an id or class to the image tag. You can get the image element using the name of the id or class , and you can change the source or src of the image using the src property.
In order to change the selected option by the value attribute, all we have to do is change the value property of the <select> element. The select box will then update itself to reflect the state of this property.
Use the value property to set the value of a select element, e.g. select. value = 'new value' . The value property can be used to set or update the value of a select element. To remove the selection, set the value to an empty string.
The src property sets or returns the value of the src attribute of an image. The required src attribute specifies the URL of an image.
use a change function on your select list
$('#kitchen_color').change( function() {
$("#imgid").attr("src","new src value");
});
$(document).ready(function(){
$("#kitchen_color").change(function(){
$("img[name=image-swap]").attr("src",$(this).val());
});
});
Use above code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With