Search code examples
jstlel

How to get values for dynamic form field names using JSTL and EL


I have 8 checkboxes and 1 button, when the user check any of the checkboxes and click the button, I want to check if any of the checkbox is checked and display it in another .jsp

I have already referred to few similar questions with no luck so far. So i tried to manage with my own logic

First.jsp

<c:forEach begin="1" end="8" varStatus="loop">
        <input type="checkbox"  id="seat" name="seat${loop.index}" value="seat${loop.index}" >
        <label for="seat">Seat${loop.index}</label>
</c:forEach> <br> <br>
<input type="submit" value="Save" name="savebtn">

Second.jsp

<c:forEach begin="1" end="8" varStatus="loop">
        <c:if test="${not empty param.seat[loop.index]}">
            <c:out value="${param.seat1} is booked"/>
        </c:of>
    </c:forEach>

I have 2 problems regarding the code above :

i can't get loop.index value inside the param $param.seat[loop.index] doesn't work And even if i try to do it manually, i can only get value from seat1. I can't get value from the rest ( seat2, seat3, etc).


Solution

  • ${param.seat[loop.index]} implies that seat is a collection, which it is not (it probably does not even exist). You are after ${param.seatX}, where you can dynamically set X. You can do that by creating a variable containing the parameter name first:

    <c:set var="seatVarName" value="seat${loop.index}"/>
    

    Now you can use this variable to get the parameter value from the implicit EL object:

    ${param[seatVarName]}
    

    See also: