2015-02-24 57 views
-1

我正在嘗試使用javascript動態地將多個值添加到下拉列表中。使用javascript在下拉列表中添加多個選項

但只有最後一個值得到顯示。

function disable_fn() { 
     var qualification =document.getElementById('ddl_qualification').value; 
     var nw_ddl = document.getElementById('stream');  
     if (qualification == 'MCA' || qualification == 'MBA') 
      return nw_ddl.disabled = true; 
     else if (qualification == "BE" || qualification == "ME") { 
      var opt = document.createElement("option") 
      nw_ddl.add(opt, nw_ddl[1]); 
      opt.text = "C.S.E"; 
      opt.value = "C.S.E"; 
      nw_ddl.add(opt, nw_ddl[2]); 
      opt.text = "MECH"; 
      opt.value = "MECH"; 
      nw_ddl.add(opt, nw_ddl[3]); 
      opt.text = "E.E.E" 
      opt.value = "E.E.E"; 
      nw_ddl.add(opt, nw_ddl[4]); 
      opt.text = "E.C.E" 
      opt.value = "E.C.E"; 
      nw_ddl.add(opt, nw_ddl[5]); 
      opt.text = "AUTO" 
      opt.value = "AUTO"; 
      nw_ddl.add(opt, nw_ddl[6]); 
      opt.text = "AERO" 
      opt.value = "AERO"; 
     } 

} 

從上面的代碼只有「AERO」得到顯示其他選項沒有。
如何添加所有的值。

謝謝。

+0

顯示html代碼 – 2015-02-24 07:10:17

+0

由於使用JavaScript生成標記,因此不需要HTML – winhowes 2015-02-24 07:12:46

回答

0

這是因爲您只創建了一個元素var opt = document.createElement("option"),因此您對opt所做的所有修改都隻影響該元素。如果你修改了代碼,這一點,它應該工作:

function disable_fn() { 
     var qualification =document.getElementById('ddl_qualification').value; 
     var nw_ddl = document.getElementById('stream');  
     if (qualification == 'MCA' || qualification == 'MBA') 
      return nw_ddl.disabled = true; 
     else if (qualification == "BE" || qualification == "ME") { 
      var opt = document.createElement("option"); 
      nw_ddl.add(opt, nw_ddl[1]); 
      opt.text = "C.S.E"; 
      opt.value = "C.S.E"; 
      opt = document.createElement("option"); 
      nw_ddl.add(opt, nw_ddl[2]); 
      opt.text = "MECH"; 
      opt.value = "MECH"; 
      opt = document.createElement("option"); 
      nw_ddl.add(opt, nw_ddl[3]); 
      opt.text = "E.E.E" 
      opt.value = "E.E.E"; 
      opt = document.createElement("option"); 
      nw_ddl.add(opt, nw_ddl[4]); 
      opt.text = "E.C.E" 
      opt.value = "E.C.E"; 
      opt = document.createElement("option"); 
      nw_ddl.add(opt, nw_ddl[5]); 
      opt.text = "AUTO" 
      opt.value = "AUTO"; 
      opt = document.createElement("option"); 
      nw_ddl.add(opt, nw_ddl[6]); 
      opt.text = "AERO" 
      opt.value = "AERO"; 
     } 

} 
0

.add被覆蓋了先前添加的元素,因此它僅顯示最後一個。

改爲add,請使用appendChild的javascript方法。

相關問題