Use JSTL forEach loop's varStatus as an ID

JavaJspJstlEl

Java Problem Overview


I want to use the count from the JSTL forEach loop, but my code doesnt seem to work.

<c:forEach items="${loopableObject}" var="theObject" varStatus="theCount">
    <div id="divIDNo${theCount}">
    </div>
</c:forEach>

produces

<div id="divIDNojavax.servlet.jsp.jstl.core.LoopTagSupport$1Status@5570e2" >

Java Solutions


Solution 1 - Java

The variable set by varStatus is a LoopTagStatus object, not an int. Use:

<div id="divIDNo${theCount.index}">

To clarify:

  • ${theCount.index} starts counting at 0 unless you've set the begin attribute
  • ${theCount.count} starts counting at 1

Solution 2 - Java

you'd use any of these:

JSTL c:forEach varStatus properties

Property Getter Description

  • current getCurrent() The item (from the collection) for the current round of iteration.

  • index getIndex() The zero-based index for the current round of iteration.

  • count getCount() The one-based count for the current round of iteration

  • first isFirst() Flag indicating whether the current round is the first pass through the iteration

  • last isLast() Flag indicating whether the current round is the last pass through the iteration

  • begin getBegin() The value of the begin attribute

  • end getEnd() The value of the end attribute

  • step getStep() The value of the step attribute

Solution 3 - Java

You can try this. similar result

 <c:forEach items="${loopableObject}" var="theObject" varStatus="theCount">
    <div id="divIDNo${theCount.count}"></div>
 </c:forEach>

Solution 4 - Java

Its really helped me to dynamically generate ids of showDetailItem for the below code.

<af:forEach id="fe1" items="#{viewScope.bean.tranTypeList}" var="ttf" varStatus="ttfVs" > 
<af:showDetailItem  id ="divIDNo${ttfVs.count}" text="#{ttf.trandef}"......>

if you execute this line <af:outputText value="#{ttfVs}"/> prints the below:

>{index=3, count=4, last=false, first=false, end=8, step=1, begin=0}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMark WView Question on Stackoverflow
Solution 1 - JavahighlycaffeinatedView Answer on Stackoverflow
Solution 2 - Javadiego matos - kekeView Answer on Stackoverflow
Solution 3 - JavaNathanphanView Answer on Stackoverflow
Solution 4 - Javajyoti paniView Answer on Stackoverflow