I am wondering if it is possible to get two values from a checkbox in HTML form.
My code in HTML is something like this:
<input type="checkbox" name="order" value="20" > Sundae $20
<input type="checkbox" name="order" value="15" > Sandwich $10
<input type="checkbox" name="order" value="25" > Reg. Burger $30
The value set is the price of the orders. So that when I code it in Java servlet, I can total the amount ordered. (my code is something like this)
String [] price = request.getParameterValues("order");
int sumTotal = 0;
for (String sum : price){
sumTotal=sumTotal+Integer.parseInt(sum);
}
out.println("<h1>Total Amount Purchased: $" + sumTotal + "</h1>");
My problems are as follow:
I want to display the name of the order and the price before I total it but I can’t because I can only get the price value using this code:
String [] price = request.getParameterValues("order");`
How can I get the name of the item besides the price?
I want to call two values in my HTML like this:
<input type="checkbox" name="order" value="20" value="Sundae $20") Sundae $20
so that in my Servlet the result would be like this:
Ordered by Customer 1:
Sundae $20
Sandwich $10
Total: $30 <------//I could only do this
but I think it is not possible and I don’t know how to call it in java.
Also, how can I improve my code in getting the total amount?
The “value” should be the name of the option:
Now you know which items were selected (and not only their price).
It breaks your code for computing the total price. However it was quite broken already. You must not rely on client-provided pride to decide of the total price on the server. The user can very easily send you a form reply with value of “1” and break everything.
The server needs to know the price of each item and use it.
where
provides the price of the ordered items (in fact the code should be more complicated than that: it should check if the item exist and so on).
You might want to use a textbox instead of a checkbox in order to be able to order more than one item.