Table of Contents

What is jquery

  • Jquery is a small, light-weight and fast javascript library. It’s cross-platform and supports different types of browsers.
  • It’s also referred as Write less do more? Because it takes a lot of common tasks that needs many lines of javascript code to accomplish, and binds them into methods which will be called with a single line of code whenever needed.
  • It’s also very useful to simplify a lot of the complicated things from javascript, like AJAX calls and DOM manipulation.

How to show and hide div elements based on dropdown selection in jQuery

Answer: Use the jQuery change() method

The following example will demonstrate you ways to show and hide div elements based on the dropdown selection or selected option in a select box using the jQuery change() method together with the show() and hide() methods. The div boxes in this example are hidden by default using the CSS display property which value is set to none.

Example

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Show Hide Elements Using Select Box</title>
<style>
.box{
color: #fff;
padding: 20px;
display: none;
margin-top: 20px;
}
.red{ background: #ff0000; }
.green{ background: #228B22; }
.blue{ background: #0000ff; }
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("select").change(function(){
$(this).find("option:selected").each(function(){
var optionValue = $(this).attr("value");
if(optionValue){
$(".box").not("." + optionValue).hide();
$("." + optionValue).show();
} else{
$(".box").hide();
}
});
}).change();
});
</script>
</head>
<body>
<div>
<select>
<option>Select Color</option>
<option value="Black">Black</option>
<option value="White">White</option>
<option value="Orange">Orange</option>
</select>
</div>
<div class="Black box">You have selected <strong>red option</strong> so i am here</div>
<div class="White box">You have selected <strong>green option</strong> so i am here</div>
<div class="Orange box">You have selected <strong>blue option</strong> so i am here</div>
</body>
</html>

Output

How to show and hide div based on dropdown selection in jQuery