1.与普通select有区别的是另一种带分组的select
2.带分组的select见另一篇:使用ajax填充下拉框--分组select
3.两者均使用ajax填充,数据来源于后台大哥
效果如下图:
html:
<div class="form-group">
<label class="control-label col-xs-12 col-sm-4 no-padding-right" for="operatorId">运营商</label>
<div class="col-xs-12 col-sm-4"><div class="clearfix"><select id="operatorId" name="operatorId" type="text" class="form-control field"></select></div></div>
</div>
js:
callBack = function (data) {
var option, firstOption, select;
select = document.querySelector("#operatorId");
select.innerHTML = "";
firstOption = document.createElement("option");
firstOption.value = "";
firstOption.innerHTML = "-------请选择运营商-------";
select.appendChild(firstOption);
console.log(data.simOperators.length);
for (var i = 0; i < data.simOperators.length; i++) {
option = document.createElement("option");
option.value = data.simOperators[i].id;
option.innerText = data.simOperators[i].name;
select.appendChild(option);
}
};
$.get("YOUR-URL", new Params(), callBack, "json");
ps:附上传过来的数据格式,截图来自chrome的network:
2017.05.02更
最近又有用到用ajax填充select,摸索出了一种更好的写法:
var roleNameModal;
roleNameModal =document.getElementById("roleModal");
for (var i = 0; i < data.role.length; i++) {
var option = document.createElement('option');
roleNameModal.options.add(option);
option.text = data.role[i].roleName;
option.value = data.role[i].id;
$("#roleModal option[value='"+firstValue+"'] ").attr("selected",true);
}
$("#roleModal option[value='"+firstValue+"'] ").attr("selected",true); 这一句,等于是一个select的反显,firstValue是后台传过来的.