carriagereturn
carriagereturn

Reputation: 19

Differentiate multiple input form inside forEach statement

I have an array of String, the length is variable. I need to create for each String two buttons: buy and remove. They manage the quantity of the correspondent element. Like this: Resoult. I tried this, works but it's not clear.

String go = request.getParameter("go");
if ((go != null)){
    String[] info = go.split(",");
    int index = Integer.parseInt(info[1]);
if (info[0].equals("+")) {
    ++quantita[index];
} else {
    --quantita[index];
}}

...

    <c:forEach var="i" begin="0" end="${length-1}" >
        <%
            int i = (int) pageContext.getAttribute("i");
            out.print(products[i] + " (" + quantita[i] +" in cart)");
        %>
        <input type=submit name="go" value="-,${i}"/>
        <input type=submit name="go" value="+,${i}"/><br>
    </c:forEach>

Upvotes: 1

Views: 247

Answers (1)

BalusC
BalusC

Reputation: 1109062

Use <button type="submit"> instead of <input type="submit">. This HTML element allows you to set content via children rather than via value attribute. This way you can simply use the name attribute to indicate the action and the value attribute to indicate the identifier.

<button type=submit name="decrease" value="${i}">-</button>
<button type=submit name="increase" value="${i}">+</button>
String decrease = request.getParameter("decrease");
String increase = request.getParameter("increase");

if (decrease != null) {
    --quantity[Integer.parseInt(decrease)];
}
else if (increase != null) {
    ++quantity[Integer.parseInt(increase)];
}

Is that clearer?

Upvotes: 1

Related Questions