Show/hide (toggle) the display of divs based on selection using javascript
12,720
Solution 1
try this. this will help you
$('#sel').change(function(){
if($(this).val()==1){
$('#firstdiv').show();
$('#seconddiv').hide();
}
else{
$('#seconddiv').show();
$('#firstdiv').hide();
}
});
Demo Here
Solution 2
you can try like this:
<script>
function test1(){
var elem = document.getElementById("test").value;
document.getElementById("firstdiv").style.display = (elem == "1") ? "block" : "none";
document.getElementById("seconddiv").style.display = (elem == "2") ? "block" : "none";
}
</script>
<select id="test" onchange="test1();">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
<div id="firstdiv" style="display:none">
<label><input type="checkbox" id='1' />A</label>
<label><input type="checkbox" id='2' />B</label>
<label><input type="checkbox" id='3' />C</label>
</div>
<div id="seconddiv" style="display:none">
<label><input type="checkbox" id='4' />D</label>
<label><input type="checkbox" id='5' />E</label>
<label><input type="checkbox" id='6' />F</label>
</div>
Author by
mpsbhat
Myself BTech professional and a programming enthusiast. Interested in front end design, Google APIs, CMS like wordpress, etc.
Updated on June 05, 2022Comments
-
mpsbhat almost 2 years
I have a web page with a dropdown menu and two divs as given below:
<html> <head> <title>Show/Hide a div section based on selection</title> </head> <body> <select id='sel'> <option value="1">Option 1</option> <option value="2">Option 2</option> </select> <div id="firstdiv"> <label><input type="checkbox" id='1' />A</label> <label><input type="checkbox" id='2' />B</label> <label><input type="checkbox" id='3' />C</label> </div> <div id="seconddiv"> <label><input type="checkbox" id='4' />D</label> <label><input type="checkbox" id='5' />E</label> <label><input type="checkbox" id='6' />F</label> </div> </body> </html>
How can I toggle the display of the above two divs based on selection using javascript or jQuery? I.e. when I select option 1, the firstdiv should display and later one should hide and vice versa.