5

With a forEach loop I'd like to create table cells (for a row) whereas each cell contains an input field of a form. The number of table cells is always fixed (12). That is actually no problem. However, here comes the challenge: the forEach should also enter a variable number of default values into the input fields that have to be obtained from a Map(Long, Double).

This is my (simplified) attempt:

<c:forEach var="number" begin="1" end="12" >
  <td>
      <input type="text" value="${requestScope.aMapWithData[number]}" /> 
  </td> 
</c:forEach>

But this doesn't show any value from the Map in the input fields. I guess the problem is that "number" is of type String and not Long. So I wonder if this problem can be solved without using scriptlets.

mvk
  • 51
  • 1
  • 1
  • 2
  • 1
    See [this thread](http://stackoverflow.com/questions/924451/jstl-access-a-map-value-by-key). Especially the accepted answer, and [this one](http://stackoverflow.com/a/5474399/1344008) – npe Aug 09 '12 at 13:57
  • Thx for the hint! The trick with the implicit type cast works very well: value="${requestScope.aMapWithData[number+0]}" – mvk Aug 09 '12 at 15:10

2 Answers2

7

What number do you want to show? Is it index number of each map entry?

<c:forEach items="${aMapWithData}" var="item" varStatus="status"> 
    <td> 
        <c:out value="${status.count}."/>  
        <input type="text" name="${item.key}" value="${item.value}" />  
    </td> 
</c:forEach> 
kapandron
  • 3,546
  • 2
  • 25
  • 38
  • No, I wanna show the actual value of each map entry. Also the number of cells should be fixed (12). In your solution the number of cells depends on the number of map entries. – mvk Aug 09 '12 at 14:41
  • Just add the attributes `begin` and `end` in `forEach` tag. `` And you'll get the desired behavior. – kapandron Aug 10 '12 at 02:15
  • Unfortunately adding "begin" and "end" doesn't help as together with the "items" attribute they doesn't specify the (fixed) number of iterations but rather restrict which elements of the map are included in the iterations. – mvk Aug 10 '12 at 07:21
  • Your reason of trouble is in something else. Launch my code. It should work properly. Or show the code that you try execute. – kapandron Aug 10 '12 at 07:37
  • Are you sure? I actually just copied your solution from your answer and replaced the first line with that in your first comment. Don't you think that my statement about the begin/end/items attributes combination is correct? – mvk Aug 10 '12 at 08:08
0

Try this

<c:forEach items="${aMapWithData}" var="mapEntry">
   <c:set var="mapKey" value="${mapEntry.key}"></c:set>
   <c:set var="mapValue" value="${mapEntry.value}"></c:set>
</c:forEach>
vikas
  • 1,535
  • 1
  • 13
  • 22