Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change the src value of an image based on the options value in a select box

Tags:

jquery

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.

like image 511
Sakeer Avatar asked Aug 05 '13 09:08

Sakeer


People also ask

How do I change the src of a photo?

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.

How do I change the Select option value?

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.

How do you set the value of a select element?

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.

What is the value set in the IMG src?

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.


2 Answers

use a change function on your select list

$('#kitchen_color').change( function() {    
$("#imgid").attr("src","new src value");
});
like image 29
Vinay Pratap Singh Bhadauria Avatar answered Oct 30 '22 03:10

Vinay Pratap Singh Bhadauria


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

   });

});

Use above code.

like image 181
Code Lღver Avatar answered Oct 30 '22 04:10

Code Lღver