1

I have receive json object form server like below one,

{"locations": [{"locationCode": "Branch 1","locationName": "BR-001"},

               {"locationCode": "Branch 2","locationName": "BR-002"},

               {"locationCode": "Branch 3","locationName": "BR-003"}
              ]}

then I need to append locationCode for value and locationName for the text

<option value="locationCode">locationName</option>

I have tried this one but couldn't do it

    var location = data.locations;
        $.each(location, function (key, value) {
        $('#newLocation')
          .append($("<option></option>")
          .attr("value", key)
          .text(value));
        });
0

2 Answers 2

3

You are iterating over array i.e. locations not on map so change your code to

var location = data.locations;
        $.each(location, function (index) {
        $('#newLocation')
          .append($("<option></option>")
          .attr("value", location[index].locationCode)
          .text(location[index].locationName));
        });

Update:-

DEMO

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

Comments

1

Try this :

var locations = 
  [
    {"locationCode": "Branch 1","locationName": "BR-001"},

    {"locationCode": "Branch 2","locationName": "BR-002"},

    {"locationCode": "Branch 3","locationName": "BR-003"}
  ];


for (var i=0;i<locations.length;i++){
    var value = locations[i].locationCode;
    var text  = locations[i].locationName;
    var opt = "<option value='"+value+"' >"+text+"</option>";
    $('#newLocation').append(opt);
}

OR :

var loc = new Object();
var loc = {"locations": 
  [
    {"locationCode": "Branch 1","locationName": "BR-001"},

    {"locationCode": "Branch 2","locationName": "BR-002"},

    {"locationCode": "Branch 3","locationName": "BR-003"}
  ]
};
for (var i=0;i<loc.locations.length;i++){
    var value = loc.locations[i].locationCode;
    var text  = loc.locations[i].locationName;
    var opt = "<option value='"+value+"' >"+text+"</option>";
    $('#newLocation').append(opt);
}               

1 Comment

Try this solutions are low-value on Stackoverflow because they do very little to educate/empower thousands of future researchers. Please improve your answer to include how your solution works and why it is a good idea.

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.