-1

This is what the object looks like:

0: {Key: "1", Value: "cat1"}
1: {Key: "2", Value: "cat2"}
2: {Key: "3", Value: "cat3"}
3: {Key: "4", Value: "cat4"}
4: {Key: "5", Value: "cat5"}

HTML:

<select id="edit-category-dropdown" class="selectpicker" multiple data-selected-text-format="count > 3" data-style="custom-select">

I need to add dropdown options to this select element with value attrib = object.key and the innertext to = object.Value.

I want it in this format ideally. <option value=object.Key>object.Value</option>

I have tried append to the element but it doesn't seem to work.

Update: apprently the issue was not my code that appended a new dropddown list but it was the fact that i didnt do a .selectpicker("refresh") on my select element. It fixed the issue with display.

DevNex
  • 21
  • 3
  • I was able to get it working. I was able to get it working with my previous code. I just didn't realize it because it didn't display.However, the issue is with the bootstrap version of bootsrap-select. It doesn't seem to want to display my dropdown options. when i take the class="selectpicker" away from my attributes, it displays just a list of options which i don't want and prefer a dropdown list. if that makes sense. – DevNex Apr 10 '19 at 06:44

3 Answers3

0

Use some javascript:

var obj = [ {Key: "1", Value: "cat1"},
 {Key: "2", Value: "cat2"},
 {Key: "3", Value: "cat3"},
 {Key: "4", Value: "cat4"},
 {Key: "5", Value: "cat5"}]

for (var i = 0; i < obj.length; i++){
  document.getElementById("edit-category-dropdown").innerHTML +=
"<option value='" + obj[i].Key + "'>" + obj[i].Value + "</option>";

}
Programnik
  • 1,449
  • 1
  • 9
  • 13
0

Make sweet and simple. I just write a basic Javascript for loop method. Try this I hope it'll help you out. Thanks

var array = [
 {Key: "1", Value: "cat1"},
 {Key: "2", Value: "cat2"},
 {Key: "3", Value: "cat3"},
 {Key: "4", Value: "cat4"},
 {Key: "5", Value: "cat5"}
]

var modelList = document.getElementById("edit-category-dropdown");
if (array) {
  var i;
  for (i = 0; i < array.length; i++) {
    var singleValue = new Option(array[i].Value, array[i].Key);
    modelList.options.add(singleValue);
  }
}
<select id="edit-category-dropdown" class="selectpicker" multiple data-selected-text-format="count > 3" data-style="custom-select">
Hassan Siddiqui
  • 2,799
  • 1
  • 13
  • 22
0
$(availableOptions).each(function(_,item){
$('#edit-category-dropdown').append($('<option>', { value: item.Key, text: item.Value }));
$("#edit-category-dropdown").selectpicker("refresh");
});
```
I was able to figure it out. Seems like I just need to include .selectpicker to refresh it. 
DevNex
  • 21
  • 3