SitePoint Sponsor

User Tag List

Results 1 to 2 of 2

Hybrid View

  1. #1
    SitePoint Enthusiast
    Join Date
    Aug 2007
    Posts
    57
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Show subcategory dropdown only when a particular category is selected

    I have a form with a drop down box with 17 categories. I want to show subcategory dropdown only when a particular category is selected. Is this possible with javascript??

  2. #2
    SitePoint Enthusiast
    Join Date
    Sep 2009
    Posts
    39
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The subcategory dropdown will be shown only if the second option is selected in the main category dropdown:
    Code HTML4Strict:
    <head>
    	<script>
    		function ShowHideSubCat () {
    			var mainCombo = document.getElementById ("mainCatCombo");
    			var subCombo = document.getElementById ("subCatCombo");
    			subCombo.style.display = (mainCombo.value == 'cat2') ? '' : 'none';
    		}
    	</script>
    </head>
    <body>
    	<select id="mainCatCombo" onchange="ShowHideSubCat ()">
    		<option value="cat1">Cat1</option>
    		<option value="cat2">Cat2</option>
    		<option value="cat3">Cat3</option>
    	</select>
    	<select id="subCatCombo" style="display: none;">
    		<option value="subcat1">SubCat1</option>
    		<option value="subcat2">SubCat2</option>
    		<option value="subcat3">SubCat3</option>
    	</select>
    </body>


    This example is the same as the previous one but it also works when the second option is selected initially ( onload="ShowHideSubCat ()" ):
    Code HTML4Strict:
    <head>
    	<script>
    		function ShowHideSubCat () {
    			var mainCombo = document.getElementById ("mainCatCombo");
    			var subCombo = document.getElementById ("subCatCombo");
    			subCombo.style.display = (mainCombo.value == 'cat2') ? '' : 'none';
    		}
    	</script>
    </head>
    <body onload="ShowHideSubCat ()">
    	<select id="mainCatCombo" onchange="ShowHideSubCat ()">
    		<option value="cat1">Cat1</option>
    		<option value="cat2" selected="selected">Cat2</option>
    		<option value="cat3">Cat3</option>
    	</select>
    	<select id="subCatCombo" style="display: none;">
    		<option value="subcat1">SubCat1</option>
    		<option value="subcat2">SubCat2</option>
    		<option value="subcat3">SubCat3</option>
    	</select>
    </body>

    Also see the examples on the select object and event object pages. You will find them useful.
    Gumape


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
  •