SitePoint Sponsor

User Tag List

Results 1 to 11 of 11
  1. #1
    SitePoint Evangelist
    Join Date
    Feb 2005
    Location
    London, UK
    Posts
    420
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    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

  2. #2
    rajug.replace('Raju Gautam'); bronze trophy Raju Gautam's Avatar
    Join Date
    Oct 2006
    Location
    Kathmandu, Nepal
    Posts
    4,013
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I have a ready made code for you hope this helps you but it is using jQuery.
    Code html4strict:
    <!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>
    Mistakes are proof that you are trying.....
    ------------------------------------------------------------------------
    PSD to HTML - SlicingArt.com | Personal Blog | ZCE - PHP 5

  3. #3
    SitePoint Evangelist
    Join Date
    Feb 2005
    Location
    London, UK
    Posts
    420
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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?

  4. #4
    rajug.replace('Raju Gautam'); bronze trophy Raju Gautam's Avatar
    Join Date
    Oct 2006
    Location
    Kathmandu, Nepal
    Posts
    4,013
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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>
    Mistakes are proof that you are trying.....
    ------------------------------------------------------------------------
    PSD to HTML - SlicingArt.com | Personal Blog | ZCE - PHP 5

  5. #5
    Non-Member Max Height's Avatar
    Join Date
    Dec 2011
    Posts
    303
    Mentioned
    6 Post(s)
    Tagged
    1 Thread(s)
    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:

    Code JavaScript:
    <!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>

  6. #6
    Under Construction silver trophybronze trophy AussieJohn's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    776
    Mentioned
    11 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Max Height View Post
    If you're just starting out then you probably shouldn't be using jquery, at least for something as basic as this.
    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 )

    Quote Originally Posted by Max Height View Post
    Code JavaScript:
    <select onchange="showHideDivs(this)">
    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.
    Code javascript:
    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:
    Code javascript:
    //lets say our <select> has an id of 'div-selecter'
    var sel = document.getElementById('div-selecter');
    addEvent(sel, 'click', function(e) {
      //do your thang.
    });
    var details = {
    . . web: "afterlight.com.au",
    . . photos: "jvdl.id.au",
    . . psa: "usethelatestversion.com"
    }

  7. #7
    Non-Member Max Height's Avatar
    Join Date
    Dec 2011
    Posts
    303
    Mentioned
    6 Post(s)
    Tagged
    1 Thread(s)
    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

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

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

  8. #8
    Under Construction silver trophybronze trophy AussieJohn's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    776
    Mentioned
    11 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Max Height View Post
    I'm not convinced that jQuery solves this easier than vanilla js. 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
    Oh absolutely, it will run a tonne more code. But from a development perspective, it's a lot easier and quicker to implement
    var details = {
    . . web: "afterlight.com.au",
    . . photos: "jvdl.id.au",
    . . psa: "usethelatestversion.com"
    }

  9. #9
    Non-Member Max Height's Avatar
    Join Date
    Dec 2011
    Posts
    303
    Mentioned
    6 Post(s)
    Tagged
    1 Thread(s)
    Quote Originally Posted by AussieJohn View Post
    But from a development perspective, it's a lot easier and quicker to implement
    ok, we can agree to disagree on this one , although jquery does have its place.

  10. #10
    SitePoint Evangelist
    Join Date
    Feb 2005
    Location
    London, UK
    Posts
    420
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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

  11. #11
    rajug.replace('Raju Gautam'); bronze trophy Raju Gautam's Avatar
    Join Date
    Oct 2006
    Location
    Kathmandu, Nepal
    Posts
    4,013
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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.
    Mistakes are proof that you are trying.....
    ------------------------------------------------------------------------
    PSD to HTML - SlicingArt.com | Personal Blog | ZCE - PHP 5


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •