Question

I do this in PHP: ++$r%2?'odd':'even' in order to apply striped rows..

<tr class="<?=++$r%2?'odd':'even'?>"><td>...</td></tr>

But when I get the recordset trough an $.ajax-request, I return the result like this:

$('#table_selected tbody').empty();  //  empty the table
$.ajax({  //  fetch new data and insert into new rows
    ...
    success: function(data){
        $.each(data, function(i, array){
            $('#table_selected tbody').append('<tr><td>'+array['name']+'</td></tr>');
        });
    }
});

What I would like to do is to add the odd/even-class to the <tr>-element on every other row - like I do in php.

Is there a similar way to achieve this in js/jqyery?

I read this answer: How do I add odd/even class only for table rows which haven´t had odd/even class yet?, and I think that's a start on what I want to achieve, but not sure how to work the solution into my code:

$("table tbody tr:nth-child(odd)").addClass("odd");
$("table tbody tr:nth-child(even)").addClass("even");
Was it helpful?

Solution

If you truly just need to stripe the tables odd/even rows, could you not just add this to your css for the page:

#table_selected tbody tr:nth-child(odd){ background-color: green; }
#table_selected tbody tr:nth-child(even){ background-color: yellow; }

If you need the classes, as Arun P Johny suggests in the comments, you update your script like this:

$('#table_selected tbody').empty();  //  empty the table
$.ajax({  //  fetch new data and insert into new rows
    ...
    success: function(data){
        $.each(data, function(i, array){
            $('#table_selected tbody').append('<tr><td>'+array['name']+'</td></tr>');
        });

        $("#table_selected tbody tr:nth-child(odd)").addClass("odd");
        $("#table_selected tbody tr:nth-child(even)").addClass("even");
    }
});

or like this (more analogous to your php way):

$('#table_selected tbody').empty();  //  empty the table
$.ajax({  //  fetch new data and insert into new rows
    ...
    success: function(data){
        $.each(data, function(i, array){
            $('#table_selected tbody').append(
                $('<tr><td>' + array['name'] + '</td></tr>')
                    .addClass(i % 2 ? 'odd' : 'even')
            );
        });
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top