Using jQuery and a Select box to show content

 

I saw a question in a forum asking how to show content based on which value was displayed chosen in a select box.  I threw together this small sample to illustrate one way you could do this using jQuery.

The full HTML file is attached.

Code Snippet
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2.  
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head>
  5.     <title></title>
  6.         <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
  7.         <script type="text/javascript">
  8.             $(document).ready(function() {
  9.             });
  10.  
  11.             // Event Handler for the OnChange event of the Select1
  12.             function SelectedItemChanged() {
  13.                 // Gets the value of Select1
  14.                 var x = $("select#Select1").val();
  15.                 // Ensures that the corresponding paragraph is visible
  16.                 ShowItem(x);
  17.  
  18.                 // Loops through all of the options for Select1 and hides them if they aren’t the selected option
  19.                 $("select#Select1 option").each(function(i) {
  20.                     if ($(this).val() != x) {
  21.                         HideItem($(this).val());
  22.                     }
  23.                 });
  24.         }
  25.  
  26.         function ShowItem(alpha) {
  27.             $("#changingArea #" + alpha).show();
  28.         }
  29.  
  30.         function HideItem(alpha) {
  31.             $("#changingArea #" + alpha).hide();
  32.         }
  33.         </script>
  34. </head>
  35. <body>
  36.     <select id="Select1" name="Select1" onchange="javascript:SelectedItemChanged();">
  37.         <option>A</option>
  38.         <option>B</option>
  39.         <option>C</option>
  40.         <option>D</option>
  41.         <option>E</option>
  42.     </select>
  43.     
  44.     <div id="changingArea">
  45.         <div id="A">Paragraph 1</div>
  46.         <div id="B">Paragraph 2</div>
  47.         <div id="C">Paragraph 3</div>
  48.         <div id="D">Paragraph 4</div>
  49.         <div id="E">Paragraph 5</div>
  50.     </div>
  51. </body>
  52. </html>