I want to populate a SELECT Dropdown List with JSON Data using JavaScript
i have sample data
sampledata = [{ "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 }]
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
4
Answers
thanks everyone this code work for me
In your code The
in
operator only works on objects. You are using it on a string. Make sure your value is an object before you using $.each. In this specific case, you have to parse the JSON:Furthermore, there is an easier way to populate data on HTML select using javascript.
Have a look on below code :
References:
For..of
Template literals
This works for me –