126

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()".

David Newcomb
  • 10,639
  • 3
  • 49
  • 62
Java Questions
  • 7,813
  • 41
  • 118
  • 176

5 Answers5

268

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>
Paul Gray
  • 546
  • 1
  • 5
  • 10
newuser
  • 8,338
  • 2
  • 25
  • 33
26

I faced similar problems. After research I understand we have some more options with the varStatus="loop". It can either use a zero based index or one based index:

  • The ${loop.index} uses a 0 base index
  • The ${loop.count} uses a 1 base index

For Example :

<c:forEach var="currentImage" items="${cityBannerImages}" varStatus="loop">
<picture>
   <source srcset="${currentImage}" media="(min-width: 1000px)"></source>
   <source srcset="${cityMobileImages[loop.count]}" media="(min-width:600px)"></source>
   <img srcset="${cityMobileImages[loop.count]}" alt=""></img>
</picture>
</c:forEach>

For more Info please check this link.

Jacob van Lingen
  • 8,989
  • 7
  • 48
  • 78
Gautam
  • 3,707
  • 5
  • 36
  • 57
14

You can use the varStatus attribute like this:-

<c:forEach var="categoryName" items="${categoriesList}" varStatus="myIndex">

myIndex.index will give you the index. Here myIndex is a LoopTagStatus object.

Hence, you can send that to your javascript method like this:-

<a onclick="getCategoryIndex(${myIndex.index})" href="#">${categoryName}</a>
Rahul
  • 44,383
  • 11
  • 84
  • 103
1

This works for me:

<c:forEach var="i" begin="1970" end="2000">
    <option value="${2000-(i-1970)}">${2000-(i-1970)} 
     </option>
</c:forEach>
Igor
  • 1,406
  • 2
  • 23
  • 45
Pradeep
  • 11
  • 1
0
<a onclick="getCategoryIndex(${myIndex.index})" href="#">${categoryName}</a>

above line was giving me an error. So I wrote down in below way which is working fine for me.

<a onclick="getCategoryIndex('<c:out value="${myIndex.index}"/>')" href="#">${categoryName}</a>

Maybe someone else might get same error. Look at this guys!

cristid9
  • 1,070
  • 1
  • 17
  • 37
Rakesh Kumar
  • 11
  • 1
  • 2