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()"
.
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>
<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!
I face Similar problem now I understand we have some more option : varStatus="loop", Here will be loop will variable which will hold the index of lop.
It can use for use to read for Zeor base index or 1 one base index.
${loop.count}` it will give 1 starting base index.
${loop.index} it will give 0 base index as normal Index of array
start from 0.
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 refer this link
This works for me:
<c:forEach var="i" begin="1970" end="2000">
<option value="${2000-(i-1970)}">${2000-(i-1970)}
</option>
</c:forEach>
Source: Stackoverflow.com