问题
I am experiencing an issue with radio buttons present on my page, can anyone tell me why it wont retain its selection after the user has pressed submit?
<?php
session_start();
if(isset($_POST['submit']))
if(!empty($_POST['diet']))
?>
...
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<strong>Dietary Requirements:</strong>
<br><br>
Vegetarian <input type="radio" name="diet" <?php if (isset($_POST['diet']) && $_POST['diet']=="Vegetarian") echo "checked";?> value="Vegetarian">
<br><br>
Vegan <input type="radio" name="diet" <?php if (isset($_POST['diet']) && $_POST['diet']=="Vegan") echo "checked";?> value="Vegan">
<br><br><br>
...
<input type="submit" id="submit" name="submit" value="Submit">
Confirmation page:
<b>Dietary Requirements: </b>
<br><br><?php if(isset($_SESSION['diet'])) echo $_SESSION['diet']; ?>
I have another set of radio buttons below the dietary requirements, which functions and retains its value fine after submit, so I dont understand why the dietary requirement radio buttons arent working.
Here is the functioning radio buttons for clarity:
<strong> VIP area* : </strong> <br><br>
Yes (+£5) <input type="radio" name="vip" <?php if (isset($vip) && $vip=="Yes") echo "checked";?> value="Yes">
<br><span id="vip" class="error"><?php echo $vipErr;?></span><br>
No <input type="radio" name="vip" <?php if (isset($vip) && $vip=="No") echo "checked";?> value="No">
<br><br><br>
回答1:
I think your looking for something like this:
<?php
session_start();
if(isset($_POST['submit'])) {
if(!empty($_POST['diet']))
$_SESSION['diet'] = $_POST['diet'];
}
if(isset($_SESSION['diet']))
echo $_SESSION['diet']
?>
<form action="" method="post">
<strong>Dietary Requirements:</strong>
<br><br>
Vegetarian <input type="radio" name="diet" <?php if (isset($_POST['diet']) && $_POST['diet']=="Vegetarian") echo "checked";?> value="Vegetarian">
<br><br>
Vegan <input type="radio" name="diet" <?php if (isset($_POST['diet']) && $_POST['diet']=="Vegan") echo "checked";?> value="Vegan">
<br><br><br>
<input type="submit" name="submit">
</form>
来源:https://stackoverflow.com/questions/27082153/retain-radio-button-selection-after-submit-php