Show div based on combination of Selected options

1

I am trying to show different DIVs based on the selection of 2 'option' but if I want to show 2 times the same div with different 'option' they are not displayed.

div1 = 3 + 5 (not shown)

div2 = 2 + 7 (shown)

div1 = 4 + 4 (shown)

Why?

link

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

function change(){
    $('#div1').toggle($s1.val() == '3' && $s2.val() == '5')
    $('#div2').toggle($s1.val() == '2' && $s2.val() == '7')
    $('#div1').toggle($s1.val() == '4' && $s2.val() == '4')
    
    
};
#div1,#div2,#div3 ,#div4,#div5,#div6,#div7{ display:none}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select1">
<option selected disabled>Valor 1</option>
<option>3</option>
<option>2</option>
<option>4</option>

</select>
+
<select id="select2">
<option selected disabled>Valor 2</option>
<option>5</option>
<option>7</option>
<option>4</option>

</select>

<div id="div1">8</div>
<div id="div2">9</div>
    
asked by Elias Aria 27.03.2016 в 17:27
source

1 answer

0

What happens is that the last line where you define the div is evaluated, for example, here:

$('#div2').toggle($s1.val() == '4' && $s2.val() == '7')
$('#div1').toggle($s1.val() == '3' && $s2.val() == '5')
$('#div2').toggle($s1.val() == '2' && $s2.val() == '7')
$('#div1').toggle($s1.val() == '4' && $s2.val() == '4')

would only be evaluated:

$('#div2').toggle($s1.val() == '2' && $s2.val() == '7')
$('#div1').toggle($s1.val() == '4' && $s2.val() == '4')

If you want to show and hide your div I recommend in this case to use the .show() and .hide() method, since with toggle() , you could have some problems controlling the states of div . Make a change in your script, making the evaluations of the values within if :

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

function change(){

 if(($s1.val() == '3' && $s2.val() == '5') ||    ($s1.val() == '4' && $s2.val() == '4')) {
     $('#div1').show();
 }else if($s1.val() == '2' && $s2.val() == '7') {
     $('#div2').show();
 }else{
     $('#div1').hide();
     $('#div2').hide(); 
 }

};

Here I add the example .

    
answered by 27.03.2016 / 20:10
source