简体   繁体   中英

Dynamically creating options for selectbox using javascript

I am dynamically setting the values for a select box using java script

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;
  }
}

How can I make this value as the selected value for the select box? currently it is coming like an option but i want this option to be the selected one for the select box

dropDwnObj.options [“您的选项”] .selected = true;

Please set select box as multiple selection using multiple attriute like below

<select multiple>
</select>

and set selected attribute is true for options like below

anOption.selected = true;

Fiddle

Hope this will help you.

anOption.selected = true;

worked for me

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM