Show/hide div via drop down

I want to show/hide divs based on the value of a drop down menu.

Have three divs that i want to load hidden

<div id=“1”>
<div id=“2”>
<div id=“3”>

Drop down menu

<select id=“choice”>
<option value=“1”>1
<option value=“1”>2
<option value=“1”>3
</select>

If choice value = 1 then div 1 = visible
If choice value = 2 then div 1 AND div 2 = visible
If choice value = 3 then div 1 AND div 2 AND div 3 = visible

this would need to be an onchange event so if 3 are visible and then ‘1’ is selected, divs 2 and 3 should be non visible (reversed)

i have looked online and cannot find a specific example so if anybody can quickly write a snippet or direct me to a tutorial will be most grateful.

thank you for assistance

I have a ready made code for you hope this helps you but it is using jQuery.


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
	<title>jQuery - Fade In/Out</title>
	<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
	<script type="text/javascript">
	$(document).ready(function(){
		$(".divs").hide();
		$(".divs:first").show();
		$("#selval").change(function(){
			var sel = $(this).val();
			$(".divs:visible").slideUp("slow");
			$("#div-" + sel).slideDown("slow");
		});
	});
	</script>
    <style type="text/css">
    .divs{
		padding: 5px;
		border: 1px solid #cccccc;
	}
    </style>
</head>
<body>
    <div class="divs" id="div-1">Sed scelerisque felis eget dui faucibus a dapibus enim elementum. Donec mattis sollicitudin sollicitudin. Donec consequat lobortis felis, sit amet euismod lorem dapibus sodales. Donec eu elementum magna. Morbi in velit at urna dictum molestie ac et velit. Fusce leo lectus, pellentesque et placerat sit amet, consequat eu mauris. Praesent mauris lectus, ultrices vel iaculis ut, consectetur non urna. Sed nec odio ac diam ullamcorper mollis. Proin tempor semper feugiat. Nam dignissim leo sit amet lectus mattis et lobortis leo eleifend. Nullam vitae erat ligula, non blandit urna.</div>
	<div class="divs" id="div-2">Phasellus ac iaculis tortor. Sed vehicula malesuada turpis sollicitudin commodo. Etiam in dignissim nunc. Cras luctus, tortor eget tempor ullamcorper, ipsum diam malesuada lectus, quis adipiscing leo felis quis massa. Cras egestas lectus eu risus sollicitudin lacinia. Donec lacinia nisi in leo ullamcorper porttitor. Ut a diam sit amet velit dictum hendrerit nec eget mi. Quisque elit sem, convallis sit amet bibendum ut, sollicitudin vel nibh. Curabitur ut nisl metus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce massa purus, fringilla sed venenatis et, ullamcorper nec lorem. Mauris sit amet mi scelerisque tortor vulputate ullamcorper. In porta venenatis ligula. Sed sollicitudin ultricies nunc, nec pulvinar lacus auctor id. Nulla et neque lacus, ac faucibus nisl.</div>
	<div class="divs" id="div-3">Sed ac est et purus tempus bibendum. Mauris id elit ante, quis mollis enim. Aenean at nibh erat, eu tincidunt neque. Donec pulvinar egestas fermentum. In quis augue at ipsum hendrerit auctor. Curabitur imperdiet auctor egestas. Vestibulum vel felis ipsum. Fusce lacinia, nunc a blandit convallis, felis magna semper lacus, sed suscipit ligula neque in est. Phasellus mi dui, faucibus nec blandit vitae, hendrerit quis eros. Sed elit massa, hendrerit sed adipiscing vitae, porta vitae lorem. Vivamus semper, lacus vel dapibus tincidunt, tellus libero tristique libero, ac cursus arcu justo aliquam nunc. Nam et lectus vitae leo mollis pharetra luctus non enim. Nam malesuada lacus a metus varius vulputate tristique lacus pharetra.</div>
	<br />
	<select id="selval" name="selval">
		<option value="1" selected="">1</option>
		<option value="2">2</option>
		<option value="3">3</option>
	</select>
</body>
</html>

thanks a lot for that.

upon testing the page it does not seem to work in IE9. do i need to upload some jquery files to my web server?

I had checked it in IE 9, FF 9 & Chrome 16 in Windows 7 and working quite fine. And you do not have to upload anything since I have directly included the jQuery from its original site.
<script type=“text/javascript” src=“http://code.jquery.com/jquery-1.7.1.js”></script>

If you’re just starting out then you probably shouldn’t be using jquery, at least for something as basic as this.

You can do what you want to do with less code using plain javascript. jQuery is nothing more than prewritten javascript functions to perform certain tasks and if you look at how much code jquery runs in the background for something like this you’ll probably get a shock.

Here is a quick and simple basic javascript demo to show/hide divs:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
        <title></title>
        <style type="text/css">
            .showHideDivs {display: none;}
        </style>
        <script type="text/javascript">
            function showHideDivs(elem){
                var divsObj = document.getElementsByClassName('showHideDivs');
                for(i=0; i<divsObj.length; i++){
                    divsObj[i].style.display = (divsObj[i].id == 'd'+elem.value)? 'block' : 'none';
                }
            }
        </script>
    </head>
    <body>
        <select onchange="showHideDivs(this)">
            <option value="">Choose a div</option>
            <option value="1">Show div 1</option>
            <option value="2">Show div 2</option>
            <option value="3">Show div 3</option>
        </select>
        <div class="showHideDivs" id="d1">This div 1</div>
        <div class="showHideDivs" id="d2">This div 2</div>
        <div class="showHideDivs" id="d3">This div 3</div>
    </body>
</html>

True enough, this is something pretty basic, but jQuery does solve it a lot easier than vanilla JS as you don’t have to deal with cross-browser issues.
(Agreed that if you’re going to learn JS you should start at the start, and actually learn all those things though)
(Am I a devil’s advocate… maybe :p)

Inline event handlers are dirty. They make your code reliant upon JavaScript. It would be much better if there were an event handler method attached to the element unobtrusively. (Of course then we would also want to show all the Divs at first and only hide them once we know JS is available)

e.g.


function addEvent( obj, type, fn ) {
  if ( obj.attachEvent ) {
    obj['e'+type+fn] = fn;
    obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
    obj.attachEvent( 'on'+type, obj[type+fn] );
  } else
    obj.addEventListener( type, fn, false );
}

(Shamelessly copied from John Resig’s “Flexible JavaScript Events” page)

now you can do:


//lets say our <select> has an id of 'div-selecter'
var sel = document.getElementById('div-selecter');
addEvent(sel, 'click', function(e) {
  //do your thang.
});

Yes, I agree regarding inline scripting. I used it in this case because I wanted to KISS because I’m assuming the op is relatively new to js and this is probably some sort of homework assignment.

I’m not convinced that jQuery solves this easier than vanilla js though. If you look at the code jquery runs to do the same thing I’ll betchya it’s a lot more lines of code than vanilla js :).

Also, I find attaching events “unobtrusively” very obtrusive - from my 2 typing fingers point of view :slight_smile:

I prefer to just put the event handler assignments in a window.onload (which I know some people don’t like doing)

window.onload=function(){
     document.getElementById('sel1').onclick=function(){showHideDivs(this);}
}

Oh absolutely, it will run a tonne more code. But from a development perspective, it’s a lot easier and quicker to implement :slight_smile:

ok, we can agree to disagree on this one :), although jquery does have its place.

hello, thanks for all the feedback. very helpful.

Raju the code is working (jquery). If you wouldn’t mind tweaking the code slightly.

On load all 3 divs should be hidden.

If user selects 1 then div 1 should be visible.
If user selects 2 then div 1 AND div 2 should be visible.
If user selects 3 then all 3 divs should be visible.

At the moment the divs are just appearing on top of each other.

Also just to clarify. If the user selects 3 and all 3 divs are visible, if they then proceed to select 2, then div 3 should disappear.
Likewise, if all 3 divs are visible and they select 1, div 2 and 3 should disappear.

thanks

To hide all at first just remove this line:
$(“.divs:first”).show();

But to implement the logic of hiding DIVs, you can do by seeing the value in:
var sel = $(this).val();

Check the value of variable ‘sel’ and do the hiding accordingly.