How to Show / Hide Div based on dropdown box selection in jQuery

How-to-Show-Hide-Div-based-on-dropdown-box-selection-in-jQuery
2346 Views
4.3
(16452)

In web development, sometimes we need to show or hide certain elements based on the user’s selection. One common scenario is to show or hide a div based on a drop-down box selection.

In this blog, we will discuss how to achieve this using jQuery, a popular JavaScript library.

First, let’s create a basic HTML structure for our dropdown and div:

<select id="myselection">
	<option>Select vehicle</option>
	<option value="car">Car</option>
	<option value="bike">Bike</option>
	<option value="truck">Truck</option>
</select>
<div id="showcar" class="myDiv">
	You have selected vehicle <strong>"Car"</strong>.
</div>
<div id="showbike" class="myDiv">
	You have selected vehicle <strong>"Bike"</strong>.
</div>
<div id="showtruck" class="myDiv">
	You have selected vehicle <strong>"Truck"</strong>.
</div>

Here, we have a label and a dropdown box with four options, and a div with some content inside.

Now, let’s write the jQuery code to show or hide the div based on the dropdown box selection:

<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> 

Now, let’s write the CSS code

.myDiv{
	display:none;
	padding:10px;
	margin-top:20px;
}  
#showcar{
	border:1px solid red;
}
#showbike{
	border:1px solid green;
}
#showtruck{
	border:1px solid blue;
}

With this code, you can easily show or hide a div based on a dropdown box selection using jQuery.

Also Read:

How to Fix parseJSON Not Working on iPad’s Safari Browser

How do i Set, Read & Delete cookies using jQuery?

FAQs

Do I need to include the jQuery library in my HTML file to use this code?

Yes, you need to include the jQuery library in your HTML file before the script tag.

Can I use this technique with other form elements, like radio buttons or checkboxes?

Yes, you can use this technique with other form elements by listening to their respective events (click for checkboxes and change radio buttons) and using similar logic to show or hide the div.

Is it possible to animate the show/hide the effect of the div?

Yes, you can use the slideDown() and slideUp() methods instead of show() and hide() to animate the show/hide the effect of the div.

How useful was this blog?

Click on a star to rate it!

Average rating 4.3 / 5. Vote count: 16452

No votes so far! Be the first to rate this blog.

Leave a comment

Your email address will not be published. Required fields are marked *