Reputation: 49422
I am using this code to get data from json.
$.each(data.id, function(index, value){
output += '<li>'+value.title+'</li>';
}
$('#listview').html(output).listview('refresh');
Sometimes there are no records to display.
How can I know if there are no records and display an alert example: alert('No records'); ?
Upvotes: 2
Views: 837
Reputation: 2377
I am assuming that the data.id
is an array, since you used$.each
on it:
if (data.id.length == 0) {
// no data
}
Upvotes: 4
Reputation: 1901
In general use this code in javascript to check if an array is not empty :
if (myArray.length) { // javascript shortcut for data.id.length>0
alert('no elems found');
}
In your specific case the following code should works :
if (data.id.length) {
$.each(data.id, function(index, value){
output += '<li>'+value.title+'</li>';
});
$('#listview').html(output).listview('refresh');
} else {
alert('no records found ');
}
Hope this helps.
Upvotes: 3
Reputation: 43666
The most general way to check if there is data in object is to use the
length
method.
But you should be very careful. For example if you data is in the following format:
SourceData =[
{
ID:1,
Title:'Test1',
},
{
ID:2,
Title:'Test2',
},
{
ID:3,
Title:'Test3',
},
]
And you do the following check:
if(SourceData.ID.length>0)
and because of some reason(error on server,request timeout,etc) the "SourceData" is not defined, an JavaScript error is going to be thrown.
That's why I am using combination of conditions:
if(typeof SourceData==='undefined'|typeof SourceData.ID==='undefined'|SourceData.ID.length==0)
Then if there is something wrong with the "SoruceData" (it is undefined) a message "No Data" will be shown. Or when the "SourceData" is initialized, but for example someone have changed the structure of the return data from the server (it is no more "ID", it is now "TitleID") no error will be generated.
Note, that I am using "|" instead of "||". This mean, if one of the conditions is "true", the right of him condiations, will not be executed.
Upvotes: 1