Linked HTML Drop Down Menus With JavaScript

8th May 2008 - 2 minutes read time

A good usability feature of web forms is to fill the contents of one drop down menu, depending on what has been selected in a previous menu. This can be done quite easily with JavaScript.

Take the following form, in this instance I have used some server variables used in mod_rewrite, but the idea is valid.

  1. <form name="myform" method="post">
  2.  
  3. Variables
  4. <select name="variables" onchange="set_detail()">
  5. <option value="http">-------</option>
  6. <option value="http">HTTP Headers</option>
  7. <option value="request">Request</option>
  8. <option value="server">Server</option>
  9. <option value="time">Time</option>
  10. </select>
  11.  
  12. Detail
  13. <select name="detail">
  14. <option>------</option>
  15. </select>
  16.  
  17. </form>

Notice that the onchange event of the first form calls a function called set_detail(). This is the JavaScript function used to fill out the second menu. The contents of the second menu are hard coded into the top of the form, so this sort of thing is only useful if the variables used don't change very much.

  1. <script type="text/javascript">
  2. // <!--
  3. var http = new Array('HTTP_USER_AGENT','HTTP_REFERER','HTTP_COOKIE');
  4. var request = new Array('REMOTE_ADDR','REMOTE_HOST','REMOTE_USER','REMOTE_IDENT');
  5. var server = new Array('DOCUMENT_ROOT','SERVER_ADMIN','SERVER_ADDR','SERVER_PORT');
  6. var time = new Array('TIME_YEAR','TIME_MON','TIME_DAY','TIME_HOUR');
  7.  
  8. function set_detail(){
  9. var select_variables = document.myform.variables;
  10. var select_detail = document.myform.detail;
  11. var selected_variable = select_variables.options[select_variables.selectedIndex].value;
  12.  
  13. select_detail.options.length=0;
  14.  
  15. if(selected_variable == "http"){
  16. for(var i=0; i<http.length; i++){
  17. select_detail.options[select_detail.options.length] = new Option(http[i]);
  18. }
  19. }
  20. if(selected_variable == "request"){
  21. for(var i=0; i<request.length; i++){
  22. select_detail.options[select_detail.options.length] = new Option(request[i]);
  23. }
  24. }
  25. if(selected_variable == "server"){
  26. for(var i=0; i<server.length; i++){
  27. select_detail.options[select_detail.options.length] = new Option(server[i]);
  28. }
  29. }
  30. if(selected_variable == "time"){
  31. for(var i=0; i<time.length; i++){
  32. select_detail.options[select_detail.options.length] = new Option(time[i]);
  33. }
  34. }
  35. }
  36. // -->
  37. </script>

 

Add new comment

The content of this field is kept private and will not be shown publicly.