How to implement multi-dimensional drop-down menus in a web project

Source: Internet
Author: User
Tags array definition javascript array

【Abstract】 for the design of drop-down menus in web projects, especially complex multi-dimensional menus, many web developers are often at a loss and discussions on such issues on the Internet are also common. This article aims to help beginners understand the implementation principles and methods of multi-dimensional dynamic drop-down menus in web projects through the analysis of an instance, and help beginners familiarize themselves with JavaScript, DHTML, ASP, and other techniques that combine with each other, to find a general solution for dynamic drop-down menus.
【Key words】 ASP, JavaScript, DHTML, drop-down menu, multi-dimensional, web project

Preface

I have recently developed a large ASP project, and I have encountered multiple multi-dimensional drop-down menus (for web projects, this refers to the <SELECT> element on the webpage, the data in the menu must be retrieved from the database and dynamically generated and changed. I have previously published articles on How to Use PHP and JavaScript to create two-dimensional drop-down menus. Currently, such articles are also quite common on the Internet, and there are many innovations in their ideas, but few people talk about the multi-dimensional drop-down menu mentioned in this article. I have no intention of making a shift, but want to sum up some experiences and skills in development, hoping to give readers some inspiration.
Multi-dimensional drop-down menu, as its name implies, controls the data displayed in one or more drop-down menus based on the selection of one drop-down menu. For example, in a web management system, You must select the Organization Name, Department name, and employee. In other words, three drop-down lists must be provided, and each drop-down list must be associated. You can select the second option through the first option, and select the third option and the fourth option at the same time. How to establish association between the displayed data in each drop-down list and how the associated data is driven by events is the main content of this article.
Users who are familiar with rad development tools such as VB and Delphi may be confused. Indeed, in these so-called rad development tools, we can use the combo boxes control to easily implement the drop-down menu and then implement the association between them. However, the drop-down menu in a web project is implemented by using the <SELECT> element in HTML. Due to the limitations of HTML, whether it is an object attribute or an event model, they are far less powerful than RAD tools. Therefore, there is only one way to solve this problem when developing web projects, that is, using JavaScript (some may say that Java can be used for implementation, so I have to say that you are a master ).
The use of JavaScript is not the focus of this article, so readers who are not familiar with or are not familiar with JavaScript should first refer to the relevant JavaScript materials for relevant information.
Let's discuss the design of multi-dimensional drop-down menus. For the convenience of the discussion, we will take the three-dimensional drop-down menu mentioned above as an example to describe the design ideas step by step.

1. Analyze the menu operation process

First, the user selects the unit list and selects a unit name from it. We assume unit A is used. What should the other two drop-down lists do? Yes, we want the second drop-down menu to immediately reflect the selection of the first drop-down menu, and display only all departments in unit, assume that the first item in the menu is department a (default display item ). Some readers may ask, shouldn't the third drop-down menu select employee data corresponding to department a at the same time? This is a good idea. Yes, we should immediately change the data in the third drop-down menu to the employee list in department. Similarly, when you select a department, the employee list is changed. And so on.
The above is an idea. There may be some special situations. For example, when changing the Department list, you do not want to select a department immediately, A prompt entry "select" is displayed.
The idea is ready, and the following is how to implement it.

Ii. Menu data container

According to the general idea, when the user selects the unit name from the first drop-down menu, we can select and display the relevant Department data from the database, which does not seem feasible. However, experienced developers will find that, because the web page is stateless, when you connect to the database again, the web page must be refreshed again. This is a headache. On the one hand, we want to connect to the database, but on the other hand, we must keep the user's input data intact. Even so, it is estimated that users do not want to see a situation where every selection is refreshed. Is there no better way?
Yes, that is, using a multi-dimensional array of JavaScript. Why can't we retrieve all the data to be displayed when we connect to the database for the first time and put it in an array? In this way, every time the menu data is changed, as long as the data is obtained from the array, can the efficiency be greatly improved? This is an exciting method. The JavaScript Array mentioned in this method is now called the container of menu data.
Are your ideas suddenly enlightened? But after a quick try, do you feel like things are not that simple? The question is, how should we design the container structure and implement the association between data? Don't worry. This is the problem.

Iii. Design of Data container structure

When talking about the design of the container structure, we need to thank the linked list in the data structure for its inspiration-linked lists are linked by pointers. Although JavaScript does not have the pointer concept, why can't we simulate it.
To facilitate the discussion, we assume that the database structure is as follows:
1. Unit info table: (unit_id, unit_name ,...)
2. Department information table: (dept_id, unit_id, dept_name ,...)
3. employee information table: (emp_id, dept_id, emp_name ,...)

With this database structure, we can easily export the array structure. You are right. This should be a multi-dimensional array. The definition method should be as follows (taking the Department as an example ):
VaR arrdept = new array ();
Arrdept [0] = new array (unit_id0, dept_id0 dept_name0 );
Arrdept [1] = new array (unit_id1, dept_id1, dept_name1 );
...
Arrdept [N] = new array (unit_idn, dept_idn, dept_namen );

The size of N depends on the actual data volume. For example, in the unit drop-down menu, N indicates the total number of units. However, the reader must understand that the above Code must be dynamically generated through the program due to the uncertainty of N. For example, for ASP programs, we can embed such a piece of code between <SCRIPT> </SCRIPT>:
<%
Dim RS, I
'[Connect to the database and retrieve data]
Response. Write "Var arrdept = new array ();" & vbnewline
I = 0
While not Rs. EOF
Response. Write "arrdept [" & I & "] = new array ('" & RS (unit_id )&"','"&_
RS (dept_id) & "','" & RS (dept_name) & "');" & vbnewline
Rs. movenext
I = I + 1
Wend
...
%>
The code above is used to retrieve data from the Department table and generate a related JavaScript multi-dimensional array. This is just a demonstration by the author. Readers can use more flexible methods to extract data.
To put it bluntly, we still need to return to the structure definition of the Javascript array. Clever readers should have discovered the array definition method from the above Code, but I still have to leave it alone:
We define the first element of the array as a pointer to point to its "parent node ". What is a parent node? The parent node indicates the upper-level node. For example, the upper level of a department is a unit, and the upper level of an employee is a department. So what is the second element? Let's take a look at the following <SELECT> definition of explain:
<Select name = "S1" onchange = "setsubmenu (this)">
<Option value = "1"> unit: 1 </option>
<Option value = "2"> unit: 2 </option>
....
</SELECT>

<Option> where does the value attribute of an element come from? Yes, it is the second element. In this way, the third element refers to the data displayed in the menu, that is, the above "unit 1", "unit 2 "...

The reader may be confused here. What is the array like if I say so much? Don't worry. Let's take the Department as an example to provide an array simulation code dynamically generated based on the data in the department database:
<Script language = "JavaScript">
<! -
...
VaR arrdept = new array ();
Arrdept [0] = new array ('u01', 'd01', 'department 1 ');
Arrdept [1] = new array ('u01', 'd02', 'department 2 ');
...
Arrdept [8] = new array ('u06', 'd08', 'department 8 ');
...
Arrdept [15] = new array ('u08', 'd15', 'department 15 ');
...
->
</SCRIPT>
 
The array is truly clear. Number of the representative unit starting with "u", that is, the pointer to the unit. That is, we can use this number to determine the department to which the unit belongs; data starting with "D" indicates the Department number, which is used as a pointer to the next level menu (that is, the employee menu. (Note: in actual use, the data format depends on the situation)
There is a question: how should I define an array with no parent nodes like a unit? It is easy to set all the first elements of the array to 0.
The next step is to write JavaScript code to control the display of menus. Assume that the three arrays you generated are named arrunit, arrdept, and arremp respectively.

4. Write JavaScript code and control menu display

In fact, experienced programmers should read here to learn how to proceed. But you may wish to read it. Maybe, my method may not be a new attempt for you. In addition, I guess most of my articles are inexperienced programmers. Come on, let's go.
There are several ideas for displaying menus. ASP and other programs can be used to directly generate the <SELECT> structure, dynamically add and change options using the add and remove methods of option objects, and so on. However, after many practices and explorations, there is a more effective method, that is, using script code to dynamically rewrite the entire <SELECT> framework.

Let's start by loading the page (document) and explain step by step how JavaScript code controls the display of menus.

Since there are three menus, we have to design such HTML code in advance (in fact, do it not matter, put it there just for easy understanding ):
<Body bgcolor = "# ffffff" onLoad = "body_onload ()">
...
<TD>
<Select name = "S0" onchange = "setsubmenu (this)"> </SELECT>
</TD>
<TD>
<Select name = "S1" onchange = "setsubmenu (this)"> </SELECT>
</TD>
<TD>
<Select name = "S2" onchange = "setsubmenu (this)"> </SELECT>
</TD>
</Body>

You may ask why there is no data here? Don't be surprised. You will naturally understand it later. Let's take a look at what the onload event body_onload () of the <body> object has done?
Function body_onload (){
VaR TD = getparent (document. All ("S0"), "TD ");
TD. innerhtml = makemenu (arrunit, 0, 0, "S0", 1 );
TD = getparent (document. All ("S1"), "TD ");
TD. innerhtml = makemenu (arrdept, getselectvalue (document. All ("S0"), 0, "S1", 1 );
TD = getparent (document. All ("S2"), "TD ");
TD. innerhtml = makemenu (arremp, getselectvalue (document. All ("S1"), 0, "S2", 1 );
}

Let's take a look. First, the program uses the getparent () function to get the TD object handle of the S0 container. Then, the makmenu () function is used to generate the menu code and assign the code to the TD object just obtained; then S1 and S2 .. The getparent () function is defined as follows:
Function getparent (SRC, tag ){
If (SRC & SRC. tagname! = Tag ){
Return (getparent (SRC. parentelement, tag ));
}
Return SRC;
}
The tag parameter must be capitalized, such as TD, TR, and table. The function returns the parent object defined by the tag label closest to the element specified by Src.
Let's take a special note of the makemenu () function. Its function is self-evident-generate the HTML definition of the menu. Let's first look at the function definition:
Function makemenu (arrsub, pvalue, cvalue, name, bulskip ){
VaR shtml = "<select name = '" + name + "'onchange = 'setsubmenu (this)'> ";
If (bulskip) shtml + = "<option value = 0> <not selected> </option> ";
For (VAR I = 0; I <arrsub. length; I ++ ){
If (arrsub [I] [0] = pvalue ){
VaR tag = (arrsub [I] [1] = cvalue )? "Selected>": "> ";
Shtml + = "<option value = '" + arrsub [I] [1] + "'" + tag + arrsub [I] [2] + "</option> ";
}
}
Shtml + = "</SELECT> ";
Return shtml;
}

Let's take a look at the meaning of the parameter. Arrsub refers to the source of menu data, which is actually the array we defined above; pvalue, which specifies the number of the parent node. Based on this number, we can find all the child node data; cvalue: Specifies the default display item of the menu; Name: Specifies the name of the generated <SELECT> menu; bulskip: Specifies whether the default display item of the menu is "<not selected>" or specific data.

The purpose of the getselectvalue () function is to obtain the value currently displayed for the <SELECT> object. If no value is displayed, the function returns 0.
Function getselectvalue (oselect ){
If (oselect. selectedindex <0) return 0;
Return oselect. Options (oselect. selectedindex). value;
}

After the user loads the page, the body_onload () function is run first. Based on the generated JavaScript multi-dimensional array, the function uses the makemenu () function to dynamically generate the HTML code of the menu, and load it to the page based on DHTML principles. OK. Run the page to check whether the menu is properly displayed? If you have any questions, take the time to debug them. For example, check whether the database connection is normal, whether the JavaScript code is case sensitive, and whether the array definition is correct...

Next, select the menu... Wait, it seems that there are still some omissions. By the way, we must add the program code for the onchange event of the <SELECT> object:
Function setsubmenu (pselect ){
VaR ooption, svalue;
If (pselect. selectedindex <0) return;
Switch (pselect. Name ){
Case "S0 ":
VaR TD = getparent (document. All ("S1"), "TD ");
TD. innerhtml = makemenu (arrdept, getselectvalue ("S0"), "0", "S1", 0 );
TD = getparent (document. All ("S2"), "TD ");
TD. innerhtml = makemenu (arremp, getselectvalue ("S1"), "0", "S2", 0 );
Break;
Case "S1 ":
VaR TD = getparent (document. All ("S2"), "TD ");
TD. innerhtml = makemenu (arremp, getselectvalue ("S1"), "0", "S2", 0 );
Break;
Default:
}
}

Okay, let's check again. There are still no omissions. Select the Unit from the first drop-down menu. Immediately, the second drop-down menu and the third drop-down menu have changed to see if you want it. (No? Haha, check again); then select a department from the second drop-down menu to see if the employee's drop-down menu has changed?
Congratulations, you have successfully implemented the three-dimensional drop-down menu. In fact, the implementation methods for Two-Dimensional menus are completely consistent. Readers can use the methods described in this article to implement a full introduction to the web project menu. In the future, you will encounter similar problems. I think you will not hesitate to say this time. Let me fix it.

The article should end at this point, but I would like to add two more words. This article provides only a solution, or a method. I do not like the hard copy method. On the contrary, I hope that the readers can draw more new ideas and new functions, which I would like to see. If you have any ideas, please contact me. Tttk2000@hotmail.com

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.