Reputation: 31
New in json and js, so I would appriciate if someone would teach me a bit. Json array:
var info = [
{"t":"09:00","b":"Vaba"},
{"t":"09:30","b":"Vaba"} ] ;
And JS part:
var output='';
for (var i = 0; i <= info.length; i++) {
for (info.t of info[i] ) {
output += '<option> ' + info[i].t + ' ' + info[i].b + '</option>'; } };
var update = document.getElementById('start_time');
update.innerHTML = output;
The result I get in HTML looks like this:
<option>9.00 Vaba</option>
<option>9.00 Vaba</option>
<option>9.30 Vaba</option>
<option>9.30 Vaba</option>
This is the only working solution I have found so far, but I don't need a double list (time and text string twice). Writing any function instead of second for loop ends with error info[i] undefined...
Thanks ahead.
Upvotes: 3
Views: 88
Reputation: 31
Thank you all for response, the final solution was jquery each()
Upvotes: 0
Reputation: 10724
Try this ,It will take less execution time and also will take care of memory.
var optionList=[];
var len= info.length;
for (var i = 0; i < len; i++) {
optionList.push('<option> ' + info[i].t + ' ' + info[i].b + '</option>');
}
var update = document.getElementById('start_time');
update.innerHTML = optionList.join('');
Upvotes: 0
Reputation: 7521
Just remove your extra for
loop. Also be careful about referencing an out-of-bounds index in info
. When i = info.length
, info[i]
is out of bounds. Just make sure it never gets that far:
var output='';
for (var i = 0; i < info.length; i++) {
output += '<option> ' + info[i].t + ' ' + info[i].b + '</option>';
}
var update = document.getElementById('start_time');
update.innerHTML = output;
Upvotes: 1