usually, I'm using data from my own MySQL but my company decided to use third party API which produce this JSON data :
{"ongkir":{
"query":{"city":"444"},
"status":{"code":200,"description":"OK"},
"results":[{"subdistrict_id":"6131","province_id":"11","province":"Jawa Timur","city_id":"444","city":"Surabaya","type":"Kota","subdistrict_name":"Asemrowo"},...
and I have this jquery :
$.each(json, function(i,o){
subdistric += "<option value="+o.subdistrict_id+">"+o.subdistrict_name+"</option>";});
and it fails to display the <option> because the JSON data contains prefix which actually I don't need. how get subdistrict_id and subdistrict_name from "results" part of JSON using jquery?
thank you very much for your help
asked Mar 28, 2016 at 8:43
Saint Robson
5,54518 gold badges74 silver badges121 bronze badges
2 Answers 2
Try
$.each(json.ongkir.results, function(i,o){
subdistric += "<option value="+o.subdistrict_id+">"+o.subdistrict_name+"</option>";});
answered Mar 28, 2016 at 8:44
madalinivascu
32.4k4 gold badges42 silver badges59 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Saint Robson
works like a charm, bro!! thanks a lot! i will accept this as an answer
It will be good if you put the html in a variable. Later when you want to add other attributes to it will be easy and code is more readable than string concatenation.
var template = "<option value='#VALUE'>#NAME</option>";
$.each(json.ongkir.results, function(i,o){
subdistric += template.replace("#VALUE", o.subdistrict_id).replace("#NAME",o.subdistrict_name);
});
answered Mar 28, 2016 at 8:50
Cheezy Code
1,7151 gold badge14 silver badges18 bronze badges
Comments
lang-js
ongkiris common or change?