MarcBalaban
MarcBalaban

Reputation: 75

Dropdown menu (select) -- selecting an item and picture shows based on the selection

I want 3+ selectors on the page each showing different product images when an item is selected. If there are 3 selectors, there will be 3 different divs to show the images.

I'm having trouble with the code:

<!-- Selector for Mug -->
<script type="text/javascript">     
$(function(){
    function changeImage(image)
{
    // hide all mainimages          
    $('div.mainimage-mug > div ').hide();

    // show the selected image
    $('div.mainimage-mug > div.' + image).show();        
}


$('select.mug').change(function(){       
    // get the selected option
    var selected = $('select.mug option:selected');

    changeImage(selected.val());   
   });


});

Thanks!

Upvotes: 0

Views: 3661

Answers (1)

HIRA THAKUR
HIRA THAKUR

Reputation: 17757

I would prefer a completely different approach. Since we are dealing with images and changing them on change of select,i would prefer changing the src of image rather than using show hide method.It is more simpler.

<select onchange="change_image(this.value)">
     <option value="red">red</option>
     <option value="green">green</option>
     <option value="blue">blue</option>
</select>

function change_image(color){
var dynamic_src="";
switch(color){
 case "red":
 dynamic_src="red_image.jpeg";
 break;
case "blue":
 dynamic_src="blue_image.jpeg";
 break;
 case "green":
 dynamic_src="Green_image.jpeg";
 break;
}

$('#image_to_be_replaced').attr('src',dynamic_src);
}

Upvotes: 3

Related Questions