-2

I want to display an array in select option drop down list

var data =  [
      { 
       "batch_number": "WJ0771104"
      },
      { 
       "batch_number": "WJ0771104"
      },
      { 
       "batch_number": "WJ0771104"
      }
    ];
var select = document.getElementById("rec_mode");
for(index in data) {
 console.log(index);
  select.options[select.options.length] = new Option(data[index], index);
}
<select id="rec_mode"></select>

but i get the list with empty values inside. i can see drop down has expanded but no value inside.
any thing im doing wrong here

kevin
  • 67
  • 8
  • May we know what does this print you on console? (what is the value of index).. And also, in this context what is "data" and what is "myobject" ? – Brank Victoria Dec 07 '18 at 08:47
  • data is the given array on top. the ajax response. – kevin Dec 07 '18 at 08:50
  • There is no JSON in this question. I'd suggest you look up what [JSON actually is](https://www.json.org/) – Liam Dec 07 '18 at 08:51
  • 2
    Then why you use `myobject[index]` instead of `data[index].batch_numer` if you want to show the `batch_number` value of each item in the array? – Brank Victoria Dec 07 '18 at 08:51
  • this code won't run, what is `myobject`? Please create a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) of your problem – Liam Dec 07 '18 at 08:56
  • 1
    i used this select.options[select.options.length] = new Option(data[index].batch_number, index); it worked thanks – kevin Dec 07 '18 at 08:57
  • 1
    I'd also suggest you look at your `for...in...` syntax, it [isn't doing what you think it's doing](https://stackoverflow.com/a/3010848/542251) – Liam Dec 07 '18 at 08:58

2 Answers2

0

I am trying to get your result

var data =[
  { 
   "batch_number": "WJ0771104"
  },
  { 
   "batch_number": "WJ0771104"
  },
  { 
   "batch_number": "WJ0771104"
  }
];
var select = document.getElementById("rec_mode");
for(index in data) {
console.log(index);
console.log(data[index].batch_number);
select.options[select.options.length] = new Option(data[index].batch_number, index);
}
<select id="rec_mode"></select>
AJAY MAURYA
  • 541
  • 3
  • 11
0

Try using a for each loop on the data array instead.

Here try this.

var data = [{
    "batch_number": "WJ0771104"
  }, {
    "batch_number": "WJ0771104"
  },
  {
    "batch_number": "WJ0771104"
  }
]
var select = document.getElementById("rec_mode");
data.forEach((doc) => {
  var opt = document.createElement('option');
  opt.value = opt.text = doc["batch_number"];
  select.add(opt);
})
<select id="rec_mode"></select>
cнŝdk
  • 31,391
  • 7
  • 56
  • 78
Lavi
  • 27
  • 1
  • 6