2

I have an array of objects which was fetched from a JSON (JSONP) file using jQuery.

I'm required to display this data using an HTML dropdown.

Current code:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type='text/javascript'>
    $.getJSON('remote-json-proxy.php?lang=en&callback=?', function(data){

    console.log(data);


    })
</script>

How do I put this data variable which is array of objects to be displayed using HTML drop-down?

object array looks like this

Object
 lines: Array[10]
0: Object
   line: "COLOMBO - BADULLA"
 1: Object
 2: Object
 3: Object
 4: Object
 5: Object
 6: Object
 7: Object

JSON File

( {"lines":[{"line":"COLOMBO - BADULLA"},{"line":"COLOMBO - MATALE"},{"line":"COLOMBO - PUTTLAM"},{"line":"COLOMBO - THANDIKULAM"},{"line":"COLOMBO - TALAIMANNAR"},{"line":"COLOMBO - BATTICALOA"},{"line":"COLOMBO - TRINCOMALEE"},{"line":"COLOMBO - MATARA"},{"line":"COLOMBO - AVISSAWELLA"},{"line":"COLOMBO - MIHINTALE"}]} );

2 Answers 2

3

This should work:

$(document).ready(function() {
    var oDDL = $("<select>");
    $.getJSON('remote-json-proxy.php?lang=en&callback=?', function(data) {
        $.each(data.lines, function(i, item) {
            oDDL.append('<option>' + item.line + '</option>');
        });
    });
    $("body").append(oDDL);
});

As you can see, it's building drop down list object and appending options to it for every item in the JSON array.

Note: Each JSON response is different, the data.lines and item.line match the JSON format of this specific case only.

Sign up to request clarification or add additional context in comments.

7 Comments

What exactly remote-json-proxy.php is returning? Can you post example?
hi i have updated the question with details check it , thanks :-)
Try changing data.items to be data.lines then.
what should i give here ? oDDL.append('<option>' + item.d.title + '</option>'); for title ?
Change item.d.title to just item.line or item.d.line I'm not sure how exactly JSON works in this context..
|
1

You'd first have to create a element in your html if you don't have one:

<select id='myselect'></select>

Then, in your js, assuming you have properties .value y .caption per item you would do:

$.getJSON('remote-json-proxy.php?lang=en&callback=?', function(data){
    for(var i=0; i<data.length; i++){ //Traverse the data array
       var value = data[i].value;
       var text = data[i].caption;
       $('<option/>').val(value).text(text).appendTo('#myselect');
    };
});

Just that. Hope this helps. Cheers

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.