AchillesVan
AchillesVan

Reputation: 4356

JSTL - Loop through table rows and set background color at each oneven rows

The purpose (according to the forEach loop) is to set a background color in every 3 rows inside the table. My code below doesnt work. The tabel is returning properly with all datas inside but no colors are set.

<c:forEach var="coffee" items="${collection}">

<tr  class="${status.count % 3 == 0 ? 'even' : 'oneven'}"
${status.count % 3 == 0 ? 'even' : 'oneven'}  >
<td> ${coffee.brand} </td>
<td> ${coffee.type} </td>
<td> ${coffee.country} </td>

</tr>

</c:forEach>

My CSS class

tr.even { background: red; }
tr.odd { background: green; }

Thank you for your help.

I found my answer:

<h2>tabel with changing colors</h2>

    <table border=1>

        <tr>
            <th>Brand</th>
            <th>type</th>
            <th>Country</th>
        </tr>

        <c:forEach var="coffees" items="${collection}" varStatus="status">



            <tr class="${status.count % 3 == 0 ? 'even' : 'odd'}"
                ${status.count % 3 == 0 ? 'even' : 'odd'}>
                <td>${coffees.brand}</td>
                <td>${coffees.type}</td>
                <td>${coffees.country}</td>

            </tr>

            </c:forEach>



    </table>

Upvotes: 0

Views: 2006

Answers (1)

JB Nizet
JB Nizet

Reputation: 691715

status is an undefined attribute here. You need to define it using the varStatus attribute of the forEach tag:

<c:forEach var="coffee" items="${collection}" varStatus="status">

Also color is used to set the foreground (text) color. Not to set the background color. And you apply the class to li, so it doesn't apply to table rows and cells. The CSS should be:

tr.even td {
    background-color: #006699;
}

tr.oneven td {
    background-color: #009999; 
}

Upvotes: 2

Related Questions