Matheno
Matheno

Reputation: 4142

JQuery foreach count

I have a piece of code that fetches results from my DB and then shows it on my page via jQuery:

var searchItem = function() {
    $('#search_results').css('top', '0px');
    $.getJSON('/json/searchitem/q/' + $('#json_search').val(), function(data){
        $('#search_results ul').fadeIn().html('');

        if($('#search_results table').css('display')=='none'){
            $('#search_results table').fadeIn();
        }

        $.each(data, function(i,item){
            $('#search_results').append('<tr><td>'+item.code+'</td></tr>');
        });
    });
};

Now, what I want is when my results are > 10 I want to show it in a table with small rows, 5 to 10 results in a normal table result and < 2 in big divs.

Can anyone point me in the right direction on how to do this count? I'm not experienced in JQuery yet.

Upvotes: 1

Views: 748

Answers (2)

Gowtham Selvaraj
Gowtham Selvaraj

Reputation: 478

var searchItem = function() {
    $('#search_results').css('top', '0px');
    $.getJSON('/json/searchitem/q/' + $('#json_search').val(), function(data){
        $('#search_results ul').fadeIn().html('');

        if($('#search_results table').css('display')=='none'){
            $('#search_results table').fadeIn();
        }
       //Checks If result length is lessthan 2
        if(data.length < 2){
            // Show in big divs
        }else{
            //  show it in a table with small rows
             $.each(data, function(i,item){
               $('#search_results').append('<tr><td>'+item.code+'</td></tr>');
             });
        }
    });
};

Upvotes: 2

Barmar
Barmar

Reputation: 780984

data is an array, and data.length is the number of elements in the array. So you can compare it with your different limit criteria.

if (data.length > 10) {
    // Code to show table with small rows
} else if (data.length >= 5) {
    // Code for normal table
} else if (data.length < 2) {
    // Code for big divs
} else {
    // Not sure what you want for 2-4, but this is where it goes
}

Upvotes: 3

Related Questions