Search code examples
javascripthtmlshow-hide

Show hide div element onselect option


Here is options (option1 and option2). If option1 is selected, the <div id="aa"> and <div id="bb"> should be showed and on selecting option2, <div id="bb"> and <div id="cc"> should be showed. how to do it using javascript?

<select>
<option>option1</option>
<option>option2</option>
</select>

<div id="aa">
<table width="100%" border="0" style="text-align:center;">
<tr><td>Table 1</td></tr>
</table></div>

<div id="bb">
<table width="100%" border="0" style="text-align:center;">
<tr><td>Table 2</td></tr>
</table></div>


<div id="cc">
<table width="100%" border="0" style="text-align:center;">
<tr><td>Table 3</td></tr>
</table></div>

Solution

  • First call a function on onChange event like

     <select onchange="ShowDiv(this.value)"> 
           <option value="1">option1</option>
           <option value="2">option2</option>
     </select>
    

    Then in Javascript

     <script type="textt/javascript">
          function ShowDiv(val)
          {
               switch(val)
               {
                    case 1:
                    {
                         document.getElementbyId('aa').style.display = "block";
                         document.getElementbyId('bb').style.display = "block";
                         document.getElementbyId('cc').style.display = "none";
                         break;
                    }
                    case 2:
                    {
                         document.getElementbyId('bb').style.display = "block";
                         document.getElementbyId('cc').style.display = "block";
                         document.getElementbyId('aa').style.display = "none";
                         break;
                    }
               }
          }
     </script>