nasty
nasty

Reputation: 7087

How to hide and show content based on drop down selection

I want to hide and show a div based on a drop down selection. That is if I select drop down option 1, div with the id 1 should show up, and for 2 div with id 2 and so on. But I want to do this without using jQuery but with css or Javascript. Is this possible? Heres my sample drop down. Thanks guys.

<select name="options">
  <option value="1"> Loan Protection Insurance</option>
  <option value="2"> GAP or Cash Assist Insurance</option>
  <option value="3"> Home Insurance</option>
  <option value="4"> Landlords Insurance</option>
  <option value="5">  Car Insurance</option>
</select>

<div id="1">Test</div>
<div id="2">Test</div>

Upvotes: 0

Views: 15171

Answers (2)

TehTooya
TehTooya

Reputation: 124

If you don't care about "selecting", making css-only drop down menus is pretty easy.

Check out: http://www.alistapart.com/articles/horizdropdowns/

You can show/hide content using the css :hover selector.

i.e:

<ul>
   <li class="menu">
       group1
       <div class="dropdown">dropdown content1</div>
   </li>
   <li class="menu">
       group2
       <div class="dropdown">dropdown content2</div>
   </li>
   <li class="menu">
       group3
       <div class="dropdown">dropdown content3</div>
   </li>
   <li class="menu">
       group4
       <div class="dropdown">dropdown content4</div>
   </li>
<ul>

Your css then needs to be similar to:

.top-menu{}
.top-menu .dropdown{display:none;}
.top-menu:hover .dropdown{display:block;}

Upvotes: 0

techfoobar
techfoobar

Reputation: 66693

Not possible with CSS alone as you need to handle the change event of the drop down and take appropriate action.

You can do it easily via pure JS:

document.getElementById('id-of-select').onchange = function() {
    var i = 1;
    var myDiv = document.getElementById(i);
    while(myDiv) {
        myDiv.style.display = 'none';
        myDiv = document.getElementById(++i);
    }
    document.getElementById(this.value).style.display = 'block';
};

Demo: http://jsfiddle.net/2ukyA/


Update: If IDs of the DIVs are like "divname1" etc..

document.getElementById('id-of-select').onchange = function() {
    var i = 1;
    var myDiv = document.getElementById("divname" + i);
    while(myDiv) {
        myDiv.style.display = 'none';
        myDiv = document.getElementById("divname" + ++i);
    }
    document.getElementById(this.value).style.display = 'block';
};

Upvotes: 9

Related Questions