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

Topic: JavaScript / jQuery« Prev|Next »

Answer: Use the jQuery change() method

The following example will demonstrate you how to show and hide div elements based on dropdown selection or select option value. The div boxes in the example are hidden by default using the CSS display property which value is set to none.

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="utf-8">
  • <title>jQuery Show Hide Using Select Box</title>
  • <style type="text/css">
  •     .box{
  •         padding: 20px;
  •         display: none;
  •         margin-top: 20px;
  •         border: 1px solid #000;
  •     }
  •     .red{ background: #ff0000; }
  •     .green{ background: #00ff00; }
  •     .blue{ background: #0000ff; }
  • </style>
  • <script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
  • <script type="text/javascript">
  • $(document).ready(function(){
  •     $("select").change(function(){
  •         $(this).find("option:selected").each(function(){
  •             if($(this).attr("value")=="red"){
  •                 $(".box").not(".red").hide();
  •                 $(".red").show();
  •             }
  •             else if($(this).attr("value")=="green"){
  •                 $(".box").not(".green").hide();
  •                 $(".green").show();
  •             }
  •             else if($(this).attr("value")=="blue"){
  •                 $(".box").not(".blue").hide();
  •                 $(".blue").show();
  •             }
  •             else{
  •                 $(".box").hide();
  •             }
  •         });
  •     }).change();
  • });
  • </script>
  • </head>
  • <body>
  •     <div>
  •         <select>
  •             <option>Choose Color</option>
  •             <option value="red">Red</option>
  •             <option value="green">Green</option>
  •             <option value="blue">Blue</option>
  •         </select>
  •     </div>
  •     <div class="red box">You have selected <strong>red option</strong> so i am here</div>
  •     <div class="green box">You have selected <strong>green option</strong> so i am here</div>
  •     <div class="blue box">You have selected <strong>blue option</strong> so i am here</div>
  • </body>
  • </html>

Related FAQ

Here are some more FAQ related to this topic:

 
Close

Your Feedback:

 

We would love to hear from you! Please say something.