使用javascript在下拉列表中添加多个选项
我正在尝试使用javascript动态地将多个值添加到下拉列表中 但只有最后一个值得到显示使用javascript在下拉列表中添加多个选项,javascript,html,html.dropdownlistfor,Javascript,Html,Html.dropdownlistfor,我正在尝试使用javascript动态地将多个值添加到下拉列表中 但只有最后一个值得到显示 function disable_fn() { var qualification =document.getElementById('ddl_qualification').value; var nw_ddl = document.getElementById('stream'); if (qualification == 'MCA'
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”得到显示,其他选项没有。如何添加所有值
谢谢。这是因为您仅使用
var opt=document.createElement(“选项”)
创建了一个元素,因此对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";
}
}
.add
将覆盖以前添加的元素,因此它只显示最后一个元素
使用javascript的
appendChild
方法代替add
。您不需要HTML,因为标记是用javascript生成的