在JavaScript中创建多个动态下拉列表

时间:2017-10-30 10:05:21

标签: javascript html arrays

我正在尝试根据主要下拉菜单的选择创建一系列动态创建的下拉菜单。数据是从一个数组中提取出来的,如果它只是两个下拉,我可以这样做,但是如果我尝试添加第三个下拉列表,则只能动态创建一个或另一个。

以下是我在HTML中的内容:

Area: <select id="Area"><option label=" "></option></select>
<br />
Section: <select id="Section"><option label=" "></option></select>
<br />
Info: <select id="Info"><option label=" "></option></select>

这是我的JS文件中的脚本和数组:

//Dynamic Section dropdown created based on Area choice selected

// Areas List Array

var Area_arr = new Array(
"North",
"Central",
"South"
);


// Sections List Array

var Section_a = new Array();
Section_a[0] = "";

Section_a[1] = "Section 1|Section 2|Section 3|Section 4";

Section_a[2] = "Section 5|Section 6|Section 7|Section 8";

Section_a[3] = "Section 9|Section 10|Section 11|Section 12";


// Calls function to generate drop downs using options above

function populateAreas(AreaElementId, SectionElementId) {

// given the id of the <select> tag as function argument, it inserts 
<option> tags
var AreaElement = document.getElementById(AreaElementId);
AreaElement.length = 0;
AreaElement.options[0] = new Option('', '');
AreaElement.selectedIndex = 0;
for (var i = 0; i < Area_arr.length; i++) {
    MAElement.options[MAElement.length] = new Option(MA_arr[i], MA_arr[i]);
}

// Assigned all Areas. Now assign event listener for the Sections.

if (SectionElementId) {
    AreaElement.onchange = function () {
        populateSections(AreaElementId, SectionsElementId);
    };
}
}

//Populate Sections once Area has been choosen
function populateSections(AreaElementId, SectionElementId) {

var selectedAreaIndex = document.getElementById(AreaElementId).selectedIndex;

var SectionElement = document.getElementById(SectionElementId);

SectionElement.length = 0;
SectionElement.options[0] = new Option('', '');
SectionElement.selectedIndex = 0;

var Section_arr = Section_a[selectedAreaIndex].split("|");

for (var i = 0; i < Hub_arr.length; i++) {
    SectionElement.options[SectionElement.length] = new Option(Section_arr[i], Section_arr[i]);
}
}

在我的HTML页面底部,我用以下方法调用上述函数:

<script type="text/javascript">populateAreas("Area", "Section");</script>

我尝试添加第三个下拉列表,其中选择基于名为Area的First下拉列表,但是当我尝试复制代码并调用Area变量来显示列表时,我将不会填充。

我尝试复制该部分只是填充区域并复制它,但它将数据切换到第三个下拉列表。

第三次下拉菜单中的选项不依赖于“部分”下拉菜单,只取决于“区域”下拉菜单。因此,一旦选择了区域,您可以按任意顺序选择“部分”下拉列表或第三个下拉列表。

1 个答案:

答案 0 :(得分:0)

也许我说这只是一个磨砂膏但是,你不是在谈论使用二维数组吗? ,如果是这样使用:

让items = [[1,2],[3,4],[5,6]];的console.log(项[0] [0]); // 1 console.log(items);

如果没有,那很好,我会撤回这个答案,但是由于一些奇怪的原因我无法找到你的问题的回复按钮,所以我会坚持只是一个答案。

无论如何,祝你好运,虽然听起来很容易,但可能就在你的鼻子底下。

相关问题