Vic
Vic

Reputation: 2878

How to get custom value from text field in JSP?

I'm working in a very simple and small web application, it is a jsp that handles a shopping cart.

What I do at this point is to iterate through all the products that are stored in the car and add them one by one to the jsp with each iteration.

This is the code that adds a row to the jsp in each iteration:

            <tr>        
            <td>
                <input type=text name=Quantity value=<%=quantity%>>
            </td>
            <td>
                <input type=text name=id value=<%=id%>>                 
            </td>
            <td>
                <input type=submit value="Delete" onclick=<%CustomSubmit(request,  id); %>>
            </td>
        </tr>

As you can see I add to the end of each row a submit type control with a custom method for handling Click events, the use of this control is to remove from the car the respective product.

The problem that I have is that when I click in the delete button of a product, the id that is passed to the CustomSubmit(...) method is not the id of the product that I'm trying to remove but the id of the last product added to the jsp.

So, my question is how can I get the correct id from the item that I'm trying to remove?

Upvotes: 0

Views: 4397

Answers (2)

Peter
Peter

Reputation: 5798

The way i use to do it is as follows:

Replace

<input type=submit with a button
<input type="button" value="Delete" onclick="deleteIt('yourid');" />

add the deleteIt javascript function, in the function you fill a hidden input field with the id. Then submit the page and the correct id gets passed to your page

Little sidenote its always prudent to escape all your Strings

dont use <input type=submit but use <input type="submit" 

maybe like

  <td>
<input type="text" name="id" value="<%=id%>">
  </td>
<td>
<input type="button" value="Delete" onclick="deleteItem('<%=id%>')">
</td>

Upvotes: 1

Nick Holt
Nick Holt

Reputation: 34311

I assume your cart is a list of objects, each having the attributes id and quantity. So I would expect you code to look something like this (noting Peter's answer about using a 'button'):

<input type="button" value="Delete" onclick="CustomSubmit('<%=cartItem.id%>');"/>

I'm not entirely sure what you are trying to do with the 'request' parameter in your original code but if this is the HTTP request all you will get when you try to write it to the JSP is the result of the request.toString method.

Upvotes: 1

Related Questions