我试图从两个数组动态填充两个选择下拉列表

时间:2015-04-18 09:59:22

标签: javascript arrays select dropdownlistfor

我填充了第一个选择列表。对于" selectList.chains"中的每个元素。数组,我需要创建一个元素,给它一个包含其标签的文本节点,设置'值'对新元素进行属性,最后将其添加到元素中。因此,当我选择一个链时,第二个选项列表应该填充它的大小。我创建了一个新的大小数组。

// HTML

<div id="selects">
  <div id="select1Div" style="float:left;margin-right:15px;"> Select
              Your &lt;Chain&gt; 
   <br>

   <select name="firstSelect" id="firstSelect">
       <option>----</option>
   </select>
</div>

<div id="select2Div"> Select Your &lt;Chain Length&gt;<br>
    <select name="secondSelect" id="secondSelect">
        <option>----</option>&nbsp;
    </select>
</div>




//JavaScript
    var sel1 = document.getElementById("firstSelect");
     var sel2 = document.getElementById("secondSelect");

     var selectList = {
         "chains": ["rice", "snake", "omega", "neoprene"]
     }

     var size = new Array()
     size["empty"] = ["Select a Length"]; 
     size["rice"] = ["16inch", "18inch", "20inch", "22inch"]; 
     size["snake"] = ["16inch", "18inch", "20inch", "22inch"]; 
     size["omega"] = ["16inch", "18inch"]; 
     size["neoprene"]= ["16inch", "18inch", "20inch"]; 

     for (var i = 0; i < selectList.chains.length; i++) {
         //create <option>
         var s = document.createElement("option");
         //create text node
         var t = document.createTextNode(selectList.chains[i]);
         // add text node to <option>
         s.appendChild(t);
         // set value="" on the <option>
         s.setAttribute("value", selectList.chains[i]);
         // add the new <option> to the <select>
         sel1.appendChild(s);
     }
    // This part will react to user selections on our drop-down list
    // and write to the page
      sel1.addEventListener("change", function(e) {
         //get the selected value from "chains"     
         var val = this.value;
          console.log(this.value);
         var s = document.createElement("option");
     // use the selected option value to retrieve the list of items from the size array 

1 个答案:

答案 0 :(得分:0)

http://jsfiddle.net/mqjagmd9/

刚刚添加

 sel2.innerHTML = "";
          for (var i = 0; i < size[this.value].length; i++) {
         //create <option>
         var s = document.createElement("option");
         //create text node
         var t = document.createTextNode(size[this.value][i]);
         // add text node to <option>
         s.appendChild(t);
         // set value="" on the <option>
         s.setAttribute("value", selectList.chains[i]);
         // add the new <option> to the <select>
         sel2.appendChild(s);
     }

到更改侦听器,它会删除当前的sel2内容并替换为新元素。