<SCRIPT language=JavaScript>
function reload(form){
var val=form.dept.options[form.dept.options.selectedIndex].value;
self.location='emp.asp?dept=' + val ;
}
</script>
The above code gets executed once the first drop down list box is selected, it collects the selected value of the first drop down list box ( here it is dept ) and then redirects the page with the value of department in the query string. Note that our file name is emp.asp, so once the department name is selected, then the url at the address bar should look like this.
https://sitename.com/emp.asp?dept=sales
Now the selected value of the dept is to be collected from the query string by using Request object.
dept=Request.QueryString("dept")
So this way we can get the value of the department and store it in the variable dept.
Set objconn = Server.CreateObject("ADODB.Connection")
objconn.ConnectionString = "DRIVER=Microsoft Access Driver (*.mdb);DBQ=" & Server.MapPath("db/emp.mdb")
objconn.Open
Set objRs = Server.CreateObject("ADODB.Recordset")
Now for first drop down list box, we will start here. Let us first write the query to collect all single department names from the table by using distinct sql.
strSQL = "SELECT distinct dept from emp_m"
Now let us populate the drop down list box by taking data from the table.
objRS.Open strSQL, objconn
Response.Write "<form method=post name=f1 action=''><select name=dept onchange='reload(this.form)'><option value=''>Select dept</option>"
Do While Not objRS.EOF
Response.Write "<option value=" & objRs("dept") & ">" & objRs("dept") & "</option>"
objRS.MoveNext
Loop
objRs.Close
Response.Write "</select>"
Note that we have used onchange event handler for the first drop down list box to execute the JavaScript function reload() once an option is selected. This drop down list ( first list ) always shows same elements. Now let us move to second drop down list, where the elements changes based on the value of first list. We will do a check for the variable dept before adding it to the query for second list. We will check the length of the dept variable by using len function of ASP. If the length of the variable is more than 0 that mean there is a department name stored inside. Here is the code for the second drop down list.
If len(dept) > 1 Then
strSQL = "SELECT * FROM emp_m where dept='" & dept &"'"
objRS.Open strSQL, objconn
Do While Not objRS.EOF
Response.Write objRs("emp_no")&" "&objRs("name")&" " &objRs("dept")&"<br>"
objRS.MoveNext
Loop
Response.Write "</form>"
objRs.Close
objconn.Close
end if
Note that The second list is populated once the value for dept is stored by selection of the first list.
11-01-2021 | |
| Thank you so much for providing this example. It was a HUGE help to me. | |