How to get a index value from foreach loop in jstl

Java Questions picture Java Questions · Sep 16, 2013 · Viewed 242.6k times · Source

I have a value set in the request object like the following,

String[] categoriesList=null;
categoriesList = engine.getCategoryNamesArray();
request.setAttribute("categoriesList", categoriesList );

and this is how I iterate in jsp page

<% if(request.getAttribute("categoriesList") != null) { %>
<c:forEach var="categoryName" items="${categoriesList}">
   <li><a onclick="getCategoryIndex()" href="#">${categoryName}</a></li>
</c:forEach>
<% }%>

How do I get index of each element and pass it to JavaScript function onclick="getCategoryIndex()".

Answer

newuser picture newuser · Sep 16, 2013

use varStatus to get the index c:forEach varStatus properties

<c:forEach var="categoryName" items="${categoriesList}" varStatus="loop">
    <li><a onclick="getCategoryIndex(${loop.index})" href="#">${categoryName}</a></li>
</c:forEach>