I'm creating a page with the products sold in the website. I'd like to include an "add to cart" button near each product, which are listed with markup similar to this:
<h4 class="productHeading">Product Name 1</h4>
<div>
Extra information on the product 1.
</div>
<h4 class="productHeading">Product Name 2</h4>
<div>
Extra information on the product 2.
</div>
...
Since the submit inputs will have different names (with the code of the product included), the big question is: should I wrap the entire product list in a form, or should I create one form for each product? In code:
<form method="post" action="process.php">
<h4 class="productHeading">Product Name 1</h4>
<div>
Extra information on the product 1.
<input type="submit" name="submit1" value="Add to Cart">
</div>
<h4 class="productHeading">Product Name 2</h4>
<div>
Extra information on the product 2.
<input type="submit" name="submit2" value="Add to Cart">
</div>
</form>
Or…
<h4 class="productHeading">Product Name 1</h4>
<div>
Extra information on the product 1.
<form method="post" action="process.php">
<input type="submit" name="submit1" value="Add to Cart">
</form>
</div>
<h4 class="productHeading">Product Name 2</h4>
<div>
Extra information on the product 2.
<form method="post" action="process.php">
<input type="submit" name="submit2" value="Add to Cart">
</form>
</div>
Which one is best practice? Any serious reason not to use one or the other, or am I doing it completely wrong?
Best practice: one form per product is definitely the way to go.
Benefits:
In your specific situation
If you only ever intend to have one form element, in this case a
submit
button, one form for all should work just fine.My recommendation Do one form per product, and change your markup to something like:
This will give you a much cleaner and usable
POST
. No parsing. And it will allow you to add more parameters in the future (size, color, quantity, etc).