Retain radio button selection after submit - PHP

谁说胖子不能爱 提交于 2019-12-11 07:39:37

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!