简体   繁体   English

如何根据一个选择创建多个动态选择框?

[英]How can I create more than one dynamic select box dependent on one selection?

I am trying to create a form that has multiple combo box selections. 我正在尝试创建具有多个组合框选择的表单。 I want the selection of the first combo box to affect the choices in the following boxes. 我希望第一个组合框的选择会影响以下框中的选择。 I have only been able to get a single pair to work. 我只能让一对工作。 I duplicated the function and changed the IDs so that it would reflect in the arguments passed, but it still only worked for the one pair. 我复制了函数并更改了ID,以使其能反映在传递的参数中,但它仍然仅适用于一对。 The code below is what I started with through a tutorial I wanted to add additional boxes, for example Chevy has the colors white, black red, dodge has the colors blue, green and black. 下面的代码是我从本教程开始的内容,我想添加其他框,例如,雪佛兰的颜色为白色,黑红色,闪避的颜色为蓝色,绿色和黑色。 How would I make additional boxes dependent on the first one? 我如何使第一个盒子依赖于其他盒子?

I tried copying the function and the html line and changing the id and name to have slct1, slct2, slct3. 我尝试复制函数和html行,并将id和名称更改为slct1,slct2,slct3。 When I added the populate function, I passed s1,s3 as the new argument. 当添加populate函数时,我将s1,s3作为新参数传递。 I also tried including it all in the one function and added the additional arguments to be passed. 我还尝试将所有功能都包含在一个函数中,并添加了要传递的其他参数。

<!DOCTYPE html>
<html>
<head>
<script>
function populate(s1,s2){
    var s1 = document.getElementById(s1);
    var s2 = document.getElementById(s2);
    s2.innerHTML = "";
    if(s1.value == "Chevy"){
        var optionArray = ["|","camaro|Camaro","corvette|Corvette","impala|Impala"];
    } else if(s1.value == "Dodge"){
        var optionArray = ["|","avenger|Avenger","challenger|Challenger","charger|Charger"];
    } else if(s1.value == "Ford"){
        var optionArray = ["|","mustang|Mustang","shelby|Shelby"];
    }
    for(var option in optionArray){
        var pair = optionArray[option].split("|");
        var newOption = document.createElement("option");
        newOption.value = pair[0];
        newOption.innerHTML = pair[1];
        s2.options.add(newOption);
    }
}
</script>
</head>
<body>
<h2>Choose Your Car</h2>
<hr />
Choose Car Make:
<select id="slct1" name="slct1" onchange="populate(this.id,'slct2')">
    <option value=""></option>
    <option value="Chevy">Chevy</option>
    <option value="Dodge">Dodge</option>
<option value="Ford">Ford</option>
</select>
<hr />
Choose Car Model:
<select id="slct2" name="slct2"></select>
<hr />  
</body>
</html>

My expected results are that the user select a car (Chevy, Dodge, Ford, etc), then additional boxes populate with options based on that choice, model and color for example. 我的预期结果是,用户选择了一辆汽车(雪佛兰,道奇,福特等),然后在其他方框中填充了基于该选择,型号和颜色的选项。 I have only been able to get the primary box and the first dependent box to work. 我只能使主框和第一个从属框起作用。

Here's an example of how you would add on another <select> to the pattern you've established. 这是一个示例,说明如何将另一个<select>添加到已建立的模式。 There are probably cleaner ways to do this, but to adhere to the tutorial this will work. 可能有更清洁的方法可以执行此操作,但是只要遵循本教程,此方法就可以使用。

 function populate(s1) { var s1 = document.getElementById(s1); var s2 = document.getElementById('model'); var s3 = document.getElementById('color'); s2.innerHTML = ""; s3.innerHTML = ""; if (s1.value == "Chevy") { var modelArray = ["|", "camaro|Camaro", "corvette|Corvette", "impala|Impala"]; var colorArray = ["|", "red|Red", "green|Green", "blue|Blue"]; } else if (s1.value == "Dodge") { var modelArray = ["|", "avenger|Avenger", "challenger|Challenger", "charger|Charger"]; var colorArray = ["|", "red|Red", "green|Green", "blue|Blue"]; } else if (s1.value == "Ford") { var modelArray = ["|", "mustang|Mustang", "shelby|Shelby"]; var colorArray = ["|", "red|Red", "green|Green", "blue|Blue"]; } for (var option in modelArray) { var pair = modelArray[option].split("|"); var newOption = document.createElement("option"); newOption.value = pair[0]; newOption.innerHTML = pair[1]; s2.options.add(newOption); } for (var option in colorArray) { var pair = colorArray[option].split("|"); var newOption = document.createElement("option"); newOption.value = pair[0]; newOption.innerHTML = pair[1]; s3.options.add(newOption); } } 
 <h2>Choose Your Car</h2> <hr /> Choose Car Make: <select id="slct1" name="slct1" onchange="populate(this.id)"> <option value=""></option> <option value="Chevy">Chevy</option> <option value="Dodge">Dodge</option> <option value="Ford">Ford</option> </select> <hr /> Choose Car Model: <select id="model" name="slct2"></select> <hr /> Choose Car Color: <select id="color" name="slot3"></select> <hr /> 

Let me know if you have any questions! 如果您有任何疑问,请告诉我!

Here the code where I add only for the first option the colors Red, White and Black. 在这里,我只为第一个选项添加红色,白色和黑色的代码。 The other options have no color Greeting 其他选项没有颜色

enter code here
<!DOCTYPE html>
<html>
<head>

<script>
function populate(s1,s2,slcolor){
    var s1 = document.getElementById(s1);
    var s2 = document.getElementById(s2);
    s2.innerHTML = "";
    slcolor.innerHTML= "";
    if(s1.value == "Chevy"){
        var optionArray = ["|","camaro|Camaro","corvette|Corvette","impala|Impala"];
        var optionColor = ["|","red|Red","white|White","black|Black"];
    } else if(s1.value == "Dodge"){
        var optionArray = ["|","avenger|Avenger","challenger|Challenger","charger|Charger"];
        var optionColor = ["|"];
    } else if(s1.value == "Ford"){
        var optionArray = ["|","mustang|Mustang","shelby|Shelby"];
        var optionColor = ["|"];
    }
    for(var option in optionArray) {
        var pair = optionArray[option].split("|");
        var newOption = document.createElement("option");
        newOption.value = pair[0];
        newOption.innerHTML = pair[1];
        s2.options.add(newOption);
    }

    for(var option in optionArray) {
        var pair = optionColor[option].split("|");
        var newOptionC = document.createElement("option");
        newOptionC.value = pair[0];
        newOptionC.innerHTML = pair[1];
        slcolor.options.add(newOptionC);
    }

}
</script>
</head>
<body>
<h2>Choose Your Car</h2>
<hr />
Choose Car Make:
<select id="slct1" name="slct1" onchange="populate(this.id,'slct2',slcolor)">
    <option value=""></option>
    <option value="Chevy">Chevy</option>
    <option value="Dodge">Dodge</option>
<option value="Ford">Ford</option>
</select>
<hr />
Choose Car Model:
<select id="slct2" name="slct2"></select>
<hr /> 

Choose Color:
<select id="slcolor" name="slcolor"></select>
<hr />  

</body>
</html>

I did some changes in your code: 我对您的代码做了一些更改:

Get the references just once 一次获取参考

the selects are always the same only the options changes, so I moved the selection to another scope. 选择始终是相同的,只是选项发生了变化,因此我将选择移到了另一个作用域。

var form = document.querySelector('form');
var brandSelect = form.querySelector('#brand');
var modelSelect = form.querySelector('#model');
var colorSelect = form.querySelector('#color');

Clone elements 克隆元素

Clone objects instead request to the DOM create new all the time. 克隆对象始终向DOM请求创建新对象。

var optionElement = document.createElement('option');
...
var optionModel = optionElement.cloneNode(true);

Protect the scope 保护范围

Wrap your code in a auto called function to avoid put your variable and function in the global scope. 将代码包装在自动调用的函数中,以避免将变量和函数放在全局范围内。 This avoid some possible conflicts between libraries. 这样可以避免库之间的某些可能冲突。

(function(){...})();

Create a data reference 创建数据参考

Data reference is more readable its easy to debug if something goes wrong also. 数据引用更具可读性,如果出了问题也很容易调试。

var brandOptions = {
  Chevy: {
    model: ['camaro', 'corvette', 'impala'],
    color: ['white', 'black', 'red'],
  },
  Dodge: {
    model: ['avenger', 'challenger', 'charger'],
    color: ['blue', 'green', 'black'],
  },
  Ford: {
    model: ['camaro', 'corvette', 'impala'],
    color: ['red', 'green', 'blue'],
  },
}

Full Example 完整的例子

 (function(){ var form = document.querySelector('form'); var brandSelect = form.querySelector('#brand'); var modelSelect = form.querySelector('#model'); var colorSelect = form.querySelector('#color'); var optionElement = document.createElement('option'); var brandOptions = { Chevy: { model: ['camaro', 'corvette', 'impala'], color: ['white', 'black', 'red'], }, Dodge: { model: ['avenger', 'challenger', 'charger'], color: ['blue', 'green', 'black'], }, Ford: { model: ['camaro', 'corvette', 'impala'], color: ['red', 'green', 'blue'], }, }; function addOptionIntheSelect(options) { modelSelect.innerHTML = ''; options.model.forEach(function(model) { var optionModel = optionElement.cloneNode(true); optionModel.value = model; optionModel.innerHTML = model; modelSelect.appendChild(optionModel); }); colorSelect.innerHTML = ''; options.color.forEach(function(color) { var optionColor = optionElement.cloneNode(true); optionColor.value = color; optionColor.innerHTML = color; colorSelect.appendChild(optionColor); }); } function onSelectChange(event) { addOptionIntheSelect(brandOptions[event.target.value]); } brandSelect.onchange = onSelectChange; })(); 
 .container { width: 100%; max-width: 300px; margin: 0 auto; } label, select { display: block; width: 100%; box-sizing: borde-box; } select { text-transform: Capitalize; } label { margin-bottom: 8px; } form > div { padding: 8px 0; } 
 <div class="container"> <form> <div> <label for="">Choose Car Make:</label> <select id="brand" name="brand"> <option value=""></option> <option value="Chevy">Chevy</option> <option value="Dodge">Dodge</option> <option value="Ford">Ford</option> </select> </div> <div> <label for="">Choose Car Model:</label> <select id="model" name="slct2"></select> </div> <div> <label for="">Choose Car Color:</label> <select id="color" name="slot3"></select> </div> </form> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM