I'm populating a drop down with JSON data from getJSON.
Populating is working fine, but trying to establish that it's finished by comparing to data.length
is not working as data.length
is undefined
and I can't see why!
The data looks like:
{
"1": {
"id": "1",
"name": "Plymouth"
},
"2": {
"id": "2",
"name": "Torquay"
}
}
My code looks like:
$('.locationList').empty();
$('.locationList').append('<option value="">Select...</option>');
$.getJSON('/Settings/locations.txt', function (data) {
var dataNum = data.length;
var counter = 1;
$.each(data, function (i, item) {
$('.locationList').append('<option value="' + data[i].id + '">' + data[i].name + '</option>');
if (counter >= dataNum) {
$('#bookTo').val(locationID + 1);
$('#transferFrom').val(locationID);
};
counter++;
});
});
This section:
if (counter >= dataNum) {
$('#bookTo').val(locationID + 1);
$('#transferFrom').val(locationID);
};
counter++;
Is meant to allow me to preset the values of the drop down boxes once the $.each
loop has completed (this works with other lists), but it's not happening.
When I run alert(data.length)
I get undefined
which makes no sense as data
clearly does have a length
in order for it to populate the drop down box properly through the $.each
, which it does!
EDIT: sorry, should add, the variable locationID
is declared earlier in the script from a Cookie and IS valid