PHP How to keep radio button state to the next pag

2019-08-03 05:56发布

问题:

I made a form with radio buttons. How can I preserve it's state after a user picked a choice? Then same form will show again in the next page and the radio button that the user picked is enabled.

//page1.html

<form method="post" action="page2.html">
    <p>
      <input type="radio" name="q1" value="A" />
      A. <br />
      <input type="radio" name="q1" value="B" />
      B. <br />
      <input type="radio" name="q1" value="C" />
      C. <br />
      <input type="radio" name="q1" value="D" />
      D. 
    <p>
      <input type="submit" name="action" value="Enter" />
    </p>
  </form>

回答1:

To get the value of q1 on the next page, you would use $_POST['q1']. You can verify that the element has been posted, and the value matches the specific radio button by using if(isset($_POST['q1'])) && $_POST['q1'] == VALUE. So your form code would look like -

  <input type="radio" name="q1" value="A" <?php if(isset($_POST['q1']) && ($_POST['q1'] == 'A')) echo 'checked="checked" ';?>/>
  A. <br />
  <input type="radio" name="q1" value="B" <?php if(isset($_POST['q1']) && ($_POST['q1'] == 'B')) echo 'checked="checked" ';?>/>
  B. <br />
  <input type="radio" name="q1" value="C" <?php if(isset($_POST['q1']) && ($_POST['q1'] == 'C')) echo 'checked="checked" ';?>/>
  C. <br />
  <input type="radio" name="q1" value="D" <?php if(isset($_POST['q1']) && ($_POST['q1'] == 'D')) echo 'checked="checked" ';?>/>