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

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

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.

HTML

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

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

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

Output

You have selected vehicle "Car".
You have selected vehicle "Bike".
You have selected vehicle "Truck".

Was this article helpful?
YesNo

Leave a comment

Your email address will not be published.