Linked HTML Drop Down Menus With JavaScript

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.

<form name="myform" method="post">
 
Variables
<select name="variables" onchange="set_detail()">
<option value="http">-------</option>
<option value="http">HTTP Headers</option>
<option value="request">Request</option>
<option value="server">Server</option>
<option value="time">Time</option>
</select>
 
Detail
<select name="detail">
<option>------</option>
</select>
 
</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.

<script type="text/javascript">
// <!--
var http = new Array('HTTP_USER_AGENT','HTTP_REFERER','HTTP_COOKIE');
var request = new Array('REMOTE_ADDR','REMOTE_HOST','REMOTE_USER','REMOTE_IDENT');
var server = new Array('DOCUMENT_ROOT','SERVER_ADMIN','SERVER_ADDR','SERVER_PORT');
var time = new Array('TIME_YEAR','TIME_MON','TIME_DAY','TIME_HOUR');
 
function set_detail(){
 var select_variables = document.myform.variables;
 var select_detail = document.myform.detail;
 var selected_variable = select_variables.options[select_variables.selectedIndex].value;
 
 select_detail.options.length=0;
 
 if(selected_variable == "http"){
  for(var i=0; i<http.length; i++){
   select_detail.options[select_detail.options.length] = new Option(http[i]);
  }
 }
 if(selected_variable == "request"){
  for(var i=0; i<request.length; i++){
   select_detail.options[select_detail.options.length] = new Option(request[i]);
  }
 }
 if(selected_variable == "server"){
  for(var i=0; i<server.length; i++){
   select_detail.options[select_detail.options.length] = new Option(server[i]);
  }
 }
 if(selected_variable == "time"){
  for(var i=0; i<time.length; i++){
   select_detail.options[select_detail.options.length] = new Option(time[i]);
  }
 }
}
// -->
</script>

 

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
1 + 3 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.