使用javascript为selectbox动态创建选项

Dynamically creating options for selectbox using javascript

本文关键字:创建 选项 动态 selectbox javascript 使用      更新时间:2023-09-26

我正在使用java脚本动态设置选择框的值

var dropDwnObj = document.getElementById("workingBranchCodeId");
dropDwnObj.options.length = 0;
var anOption = document.createElement("OPTION");
dropDwnObj.options.add(anOption) ;
for(var i = 0; i < jsonResult.subLocationList.length; i++) {
  var anOption = document.createElement("OPTION");
  dropDwnObj.options.add(anOption) ;
  if(selValue == jsonResult.subLocationList[i].displayKey) {
    anOption.innerHTML = jsonResult.subLocationList[i].displayValue;
    anOption.value = jsonResult.subLocationList[i].displayKey;
  }
}

如何将该值设置为选择框的选定值?目前它就像一个选项,但我希望这个选项是选择框的选定选项

请使用multiple属性将选择框设置为多选,如下

<select multiple>
</select>

对于以下的选项,设置所选属性为true

anOption.selected = true;

Fiddle

希望这对你有帮助。

dropDwnObj.options["your option"].selected=true;

anOption.selected=true;

为我工作