Ismailp
Ismailp

Reputation: 2383

Show div depending on two seperate select options

I have stumbled upon a problem.

I have two different select fields. Each of these have color options: blue, green, black, yellow. I want to show different divs depending on which selctions you make like so:

Selection yellow+black shows div#1 Selection black+yellow shows div#2 etc. etc.

How can I do this in a smart way?

Update:

Here is a code snippet I have right now (it does what I want but only depending on one select element):

<script>
$(document).ready(function() {
  $(function() {
    $('#thecolor').change(function(){
        $('#box_image, #box_image2, #box_image3, #box_image4').hide();
        $('.' + $(this).val()).show();
    });
  });
});

<select id="thecolor">
   <option>Choose outer color</option>
   <option value="blue">Blue</option>
   <option value="red">Red</option>
   <option value="dark_green">Green</option>
   <option value="purple">Purple</option>
 </select>

and then

<div id="box_image" style="display:none;" class="blue">
  <img src="images/wine-bottle-box_blue.png"/>
</div>

Upvotes: 0

Views: 357

Answers (2)

Jamiec
Jamiec

Reputation: 136074

To do this you can use the toggle function in jQuery to show/hide an element based on the values of 2 select lists. Just hook both select lists up to the same click handler and check the condition.

var $s1 = $('#select1').change(change);
var $s2 = $('#select2').change(change);

function change(){
    $('#div1').toggle($s1.val() == 'Yellow' && $s2.val() == 'Black')
    $('#div2').toggle($s1.val() == 'Black' && $s2.val() == 'Yellow')
};

Live example: http://jsfiddle.net/6AUn6/

Upvotes: 2

Quincy
Quincy

Reputation: 4433

How about naming your div's id by the options combination. So selecting yellow+black will display div with id like div_yellow_black.

In jquery, something like

var var1 = $("#option1").val();
var var2 = $("#option2").val();
$("#div_" + var1 + "_" + var2).show();

Upvotes: 1

Related Questions