jqueryjspjakarta-eejstl

How to pass html input value in a request parameter on a button click


I have a list of books dynamically generated using core library inside a table. The user can select a quantity of the books to add to his cart and clicks on the "Add to cart button". What I want is to pass the value "quantity" from the input and pass it in a request parameter when the button is clicked. I tried this way but only the value of the first row quantity is passed, even if the button on the 3rd row (for example) is clicked :

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<c:forEach var="book" items="${books}">
    <tr>
        <td><img alt="" src="images/${book.getIsbn()}.jpg" width="100"></td>
        <td><c:out value="${book.getIsbn()}"></c:out></td>
        <td><c:out value="${book.getTitle()}"></c:out></td>
        <td><input type="number" id="qtty"></td>
        <td>
            <button onclick='window.location ="usercart.htm?isbn=${book.getIsbn()}&qtty="+document.getElementById("qtty").value'>Add to cart</button>
        </td>
    </tr>
</c:forEach>

Solution

  • It looks like the problem here is that you have multiple inputs with the same id 'qtty' and document.getElementById("qtty") returns the first.

    You can try giving each input a distinct identifer:

    <td><input type="number" id="qtty_${book.isbn}"></td>
    <td>
        <button onclick='window.location ="usercart.htm?isbn=${book.getIsbn()}&qtty="+document.getElementById("qtty_${book.isbn}").value'>Add to cart</button>
    </td>
    

    However, a better solution may be to refactor to use a form for each element.See the discussion below on creating a form for each row:

    HTML: Is it possible to have a FORM tag in each TABLE ROW in a XHTML valid way?