user2093576
user2093576

Reputation: 3092

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

Upvotes: 1

Views: 44

Answers (3)

balachandar
balachandar

Reputation: 825

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.

Upvotes: 1

user5590957
user5590957

Reputation:

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

Upvotes: 1

user2093576
user2093576

Reputation: 3092

anOption.selected = true;

worked for me

Upvotes: 0

Related Questions