i want to get all the data of the json array that i called into a select option tag
i’m calling the api from here http://dev.farizdotid.com/api/daerahindonesia/provinsi and this is the json array that i got
semuaprovinsi: Array(34)
0: {id: "11", nama: "Aceh"}
1: {id: "12", nama: "Sumatera Utara"}
2: {id: "13", nama: "Sumatera Barat"}
3: {id: "14", nama: "Riau"}
4: {id: "15", nama: "Jambi"}
5: {id: "16", nama: "Sumatera Selatan"}
6: {id: "17", nama: "Bengkulu"}
7: {id: "18", nama: "Lampung"}
8: {id: "19", nama: "Kepulauan Bangka Belitung"}
9: {id: "21", nama: "Kepulauan Riau"}
10: {id: "31", nama: "Dki Jakarta"}
11: {id: "32", nama: "Jawa Barat"}
12: {id: "33", nama: "Jawa Tengah"}
13: {id: "34", nama: "Di Yogyakarta"}
14: {id: "35", nama: "Jawa Timur"}
15: {id: "36", nama: "Banten"}
16: {id: "51", nama: "Bali"}
17: {id: "52", nama: "Nusa Tenggara Barat"}
18: {id: "53", nama: "Nusa Tenggara Timur"}
19: {id: "61", nama: "Kalimantan Barat"}
20: {id: "62", nama: "Kalimantan Tengah"}
21: {id: "63", nama: "Kalimantan Selatan"}
22: {id: "64", nama: "Kalimantan Timur"}
23: {id: "65", nama: "Kalimantan Utara"}
24: {id: "71", nama: "Sulawesi Utara"}
25: {id: "72", nama: "Sulawesi Tengah"}
26: {id: "73", nama: "Sulawesi Selatan"}
27: {id: "74", nama: "Sulawesi Tenggara"}
28: {id: "75", nama: "Gorontalo"}
29: {id: "76", nama: "Sulawesi Barat"}
30: {id: "81", nama: "Maluku"}
31: {id: "82", nama: "Maluku Utara"}
32: {id: "91", nama: "Papua Barat"}
33: {id: "94", nama: "Papua"}
and this is my jquery code
$(function() {
var province = $('#provinces');
var select = $('#selection');
var option = $('<option>');
$.ajax({
type: 'GET',
dataType: 'json',
url: 'http://dev.farizdotid.com/api/daerahindonesia/provinsi',
success: function(provinces) {
console.log(provinces);
var allProvince = provinces.semuaprovinsi;
$.each(allProvince, function (i, item) {
option.text(item.nama);
option.attr('value', item.id);
select.append(option);
});
}
});
});
it only showing the last index of the data which is index number 33 that get into my select tag
this is my select tag
<select id="selection">
<option value=""></option>
</select>
i have no idea, why i only getting 1 data
2
Answers
You have to create new option with each option. Else it modify same.
Initialize
option
inside the.each
for every iteration: