There are also many examples of second-level (Multi-Level) linkage on the Internet, with different operation methods. The method I used should also be available online, but I have not seen it yet.
Table Structure
Level-2 or multi-level association is mainly based on tables with parent numbers in the database, which is no exception
Id, parent_id, and name columns.
Js operations
Let's talk about how to store data in js.
It mainly uses two-dimensional arrays to store data. The structure is as follows:
A [Parent id] = [[Child Id 1, child name 1], [Child ID 2, child name 2], [Child ID 3, child name 3], ……];
First, use the parent number to obtain all the child data. Then, bind the ID and name of the child data to the dropdown.
Step 1: Associate the second-level data (how to obtain the data later)
The Code is as follows:
Var cities = new Array ();
Cities ['2017-0000-0000-000000000000'] = [['028db215-0000', 'changchun '], ['bcb32195-2a46-4cd1-9472-6383e8fa55cc', 'shenyang '];
Var schools = new Array ();
Schools ['028db215-hangzhou'] = [['5f22403a-7a59-4b7f-b62d-9451298cbd00 ', 'changchun 1'], ['e8f0f665-Beijing', 'changchun 2'];
Schools ['bcb32195-2a46-4cd1-9472-6383e8fa55cc'] = [['4a743dbf-1fdc-4907-a44e-8d169d715664', 'shenyang 1'];
The first level is the city data, and the second level is the school data.
Step 2: Set Data to display in dropdown
The Code is as follows:
// Obtain the corresponding child data based on the parent number and display it in the obj Control
// Type = 0 City, 1 school
// Pid parent number
// Obj to display the data dropdown
Function SetRegions (type, pid, obj)
{
Var text ="Select";
Var tempArray = new Array ();
If (type = 0 ){
TempArray = cities [pid];
} Else if (type = 1 ){
TempArray = schools [pid];
}
If (tempArray! = Null)
{
For (var I = 0; I Text + =" "+ TempArray [I] [1] +"";
}
}
Optional (obj).html (text );
}
Step 3 select school data when the city changes
The Code is as follows:
// Use the city number to set school subdata
Function CityChanged (){
SetRegions (1, $ ("# cities"). val (), "# schools ");
}
Step 4, of course, requires initialization during the modification, which is also my biggest headache in the past.
The Code is as follows:
// Initialize the city school Value
// CityId city no.
// SchoolId school ID
Function InitRegions (cityId, schoolId)
{
// Initialize City Data
// SetRegions (0, "00000000-0000-0000-0000-000000000000", "# cities ");
// Find the city and set it to the default value
$ ("# Cities option [value =" + cityId + "]"). attr ("selected", "selected ");
If (schoolId! = "00000000-0000-0000-0000-000000000001 "){
// Initialize school data
SetRegions (1, cityId, "# schools ");
// Find the school and set it to the default value
$ ("# Schools option [value =" + schoolId + "]"). attr ("selected", "selected ");
}
}
Front-end code
The Code is as follows:
<% -- City -- %>
<% -- School -- %>