When I populate a form, I want to display or hide multiple divs based on the OPTION selected in a DROPDOWN.
Currently, my code works but the issue is that one div can be hidden or shown by multiple OPTIONS. As a result, these divs keep toggling between hidden and visible states.
Below is the HTML snippet:
<select id="vFormat" name="vFormat" onchange="getval(this);">
<option value="0">Choose</option>
<option value="1" class="format1">Option 1</option>
<option value="2" class="format2">Option 2</option>
<option value="3" class="format3">Option 3</option>
<option value="4" class="format4">Option 4</option>
<option value="5" class="format5">Option 5</option>
</select>
<div class="showdivformat1 showdivformat2 hiddenelement">
Text inside hidden Div
</div>
<div class="hidedivformat2 showdivformat5 visibleelement">
Text inside visible Div
</div>
This is the JQuery functionality:
function getval(sel) {
var divval = $('.selectInput option:selected').attr('class').split(' ');
for(var i=0; i<divval.length; i++){
$(".hiddenelement").hide("50");
$(".showdiv" + divval[i]).show("50");
}
for(var i=0; i<divval.length; i++){
$(".visibleelement").show("50");
$(".hidediv" + divval[i]).hide("50");
}
}
The challenge lies in always hiding .hiddenelement and showing .visibleelement whenever the option changes.
I am exploring solutions to detect if a div is already hidden or visible and maintain its state after the option change.