2015-02-24 56 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方法。

相关问题