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??
| SitePoint Sponsor |
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??
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