3

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.

1
  • What do you want to know? Can you post the code which throws error for you? Commented Oct 7, 2013 at 14:29

3 Answers 3

1

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;
Sign up to request clarification or add additional context in comments.

Comments

0

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('');

1 Comment

Avoid concatenation of string(it takes more memory) and in the for loop we need not to calculate length of info object(Array) for each iteration so, execution time will be less.
0

Thank you all for response, the final solution was jquery each()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.