populate a SELECT Dropdown List with JSON Data using JavaScript

Nov 23 2023 4:17 AM

I want to populate a SELECT Dropdown List with JSON Data using JavaScript

success: function(data) {
    var distList = data.d;
    console.log(distList);
    //consoleoutput =  [{ "Districtname": "CENTRAL DELHI", "ID": 1 }, { "Districtname": "NORTH DELHI", "ID": 2 }, { "Districtname": "NORTH EAST DELHI", "ID": 3 }, { "Districtname": "NORTH WEST DELHI", "ID": 4 }, { "Districtname": "SOUTH DELHI", "ID": 5 }, { "Districtname": "SOUTH EAST DELHI", "ID": 6 }, { "Districtname": "SOUTH WEST DELHI", "ID": 7 }, { "Districtname": "WEST DELHI", "ID": 8 }]
    var s = '<option value="-1">Please Select a Distic</option>';
    for (var i = 0; i < distList.length; i++) {
        s += '<option value="' + distList[i].ID + '">' + distList[i].Districtname + '</option>';
    }
    $("#dist").html(s);

}

i tried another approach

  $.each(distList, function (key, value) {
  $('#dist').append('<option value="' + key + '">' + value + '</option>');
});

but 

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in [{"Districtname":"CENTRAL.................... ,{"Districtname":"WEST DELHI","ID":8}]

plz help


Answers (3)