Menu Close

Show / Hide div based on dropdown selected using jQuery

Show Hide div based on dropdown selected using jQuery

If you want to hide/show div on dropdown selected, use the jQuery hide() and show(). Before you perform hide or show div on dropdown selection, you need to hide them first using CSS display:none.

The display of the div dynamically happen based on the click of the selected dropdown option. A hidden div displays and the CSS property display:block added to the displayed div element.

How to hide and show div or section banes on dropdown selected using jQuery

Follow the below sample example for show/hide div when you select dropdown options.

HTML

<select id="myselection">
	<option>Select Option</option>
	<option value="One">One</option>
	<option value="Two">Two</option>
	<option value="Three">Three</option>
</select>
<div id="showOne" class="myDiv">
	You have selected option <strong>"One"</strong>.
</div>
<div id="showTwo" class="myDiv">
	You have selected option <strong>"Two"</strong>.
</div>
<div id="showThree" class="myDiv">
	You have selected option <strong>"Three"</strong>.
</div> 

Script


<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>      

<script>
$(document).ready(function(){
    $('#myselection').on('change', function(){
    	var demovalue = $(this).val(); 
        $("div.myDiv").hide();
        $("#show"+demovalue).show();
    });
});
</script> 

Style

<style>
.myDiv{
	display:none;
    padding:10px;
    margin-top:20px;
}  
#showOne{
    border:1px solid red;
}
#showTwo{
    border:1px solid green;
}
#showThree{
    border:1px solid blue;
}
</style> 

Output

You have selected option "One".
You have selected option "Two".
You have selected option "Three".

There are three options given in the select box to select. You have to select the option to display the relevant div element. To show/hide div on the select option selected, the dynamic changes can handle by using some jQuery script as given in the example above.

In addition to all these, don’t forget to add the CSS property display:none to all the div’s which you want to show/hide and display only on select of the options.

Posted in HTML, JavaScript, jQuery

You can also read...