如何处理表单中的两个提交按钮?

如何处理表单中的两个提交按钮?

问题描述:

I don't understand this,

if I do this and I click the check out button, the page won't go to the check out page,

<form action="cart.php" method="post" id="form-cart">
<button name="update" id="update" type="submit" value="Update cart">Update cart</button>
<button name="checkout" id="checkout" type="submit" value="Check out">Check out</button>
</form>

It only does if I change the name="checkout" to name="cart-checkout",

<form action="cart.php" method="post" id="form-cart">
<button name="update" id="update" type="submit" value="Update cart">Update cart</button>
<button name="cart-checkout" id="checkout" type="submit" value="Check out">Check out</button>
</form>

It works that way but does not make any sense to me, do you know why it does it that way?

So I tried to use <a> tag inside the <button> tag and it goes to the check out page,

<form action="cart.php" method="post" id="form-cart">
<button name="update" id="update" type="submit" value="Update cart">Update cart</button>
<button name="checkout" id="checkout" type="submit" value="Check out"><a href="checkout.php">Check out</a></button>
</form>

But does it a valid html to put <a> tag inside the <button> tag?

Why not change the buttons to:

<input name="update" id="update" type="submit" value="Update cart">
<input name="cart-checkout" id="checkout" type="submit" value="Check out">

Then in PHP (on cart.php) you can do:

<?php
  if($_POST){
     if(isset($_POST['update']){
       // process update
     } else if(isset($_POST['cart-checkout']){
       // process cart checkout
       // or uncomment the below line to forward to checkout.php
       // header("Location: checkout.php");
     }
  }
?>

What about making one <button> that simply acts like a <a href=""> ?

-edit-

Whoops, sorry, misread. <button onclick="window.location='/nextpage';"> ?

I would actually use JavaScript here with an onclick event, which will take you to the checkout page.