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));
});
You are iterating over array ie 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:-
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.