0

Using jquery I am trying to read values from a json file and populate in a dropdown.

For that I am doing the following but undefined value is getting in dropdown. What's wrong with my code? json file

   {
      "VMs":[
        {
          "ID":"VM-WIN7-64",
          "OS":"Windows 7",
          "FLAVOUR":"VM-IE8-001-preq",
          "ADAPTER":"Win 9"
        }
      ],
      "Paths":{
        "VM-WIN7-64":"C:\\VirtualMachines\\Win7_X64_VM-001\\Win7_X64_VM-001.vmx"
      }
    }

code

function getOsNames() {
 $.getJSON('/json/data.json', function(data) 
    {
var html = '';
        $.each(data,function(val,i)
        {
alert(val);
html += '<option value="' + val.OS + '">' + val.OS + '</option>';
        });
     $('#op').html(html);     

    });

}

2 Answers 2

2

You have to loop through data.VMs as it is having the OS property

function getOsNames() {
    $.getJSON('/json/data.json', function (data) {
        var html = '';
        $.each(data.VMs, function (i, val) {
            html += '<option value="' + val.OS + '">' + val.OS + '</option>';
        });
        $('#op').html(html);
    });
}

Demo: Fiddle

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

5 Comments

getting undefined data in place of os
@Sush the each callback parameter order is swapped
you have grab only one value in select menu...if we need to add all value then what changes we need to do
in fiddle ur using static data how can i read from a josn file
@Sush it is the same... did you check the above answer
0

You can use for loop :

for(var i=0;i<data.VMs.length;i++)
{
   html += '<option value="' + data.VMs[i].OS + '">' + data[i].VMs[i].OS + '</option>';
}
$('#op').html(html);  

This will solve your problem

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.