在提交PHP后保持表单值

问题描述:

我忘了说有下拉菜单,我想保留

I forgot to say there are drop down menus also that I would like to keep the chosen value of

我有一个带有复选框,单选按钮的表单,几个文本字段。我知道如何保持文本字段值后提交表单,但我想保持单选按钮选择和复选框提交后选中。

I have a form with checkboxes, a radio buttons, and a few text fields. I know how to keep the text field values after form submit, but I would like to keep the radio button selection and checkboxes checked after submit. I am posting to the same page.

要预先选中单选按钮和复选框,您需要添加 checked =checked属性为您要为每个要显示的控件生成的HTML。

To have the radio buttons and checkboxes pre-checked, you need to add the checked="checked" attribute to the HTML you generate for each control you want to display checked.

如果您目前有这个:

<input type="checkbox" name="foo" value="bar" />

您要将其更改为:

<input type="checkbox" name="foo" value="bar"
    <?php echo empty($_POST['foo']) ? '' : ' checked="checked" '; ?>
/>

更新:对于下拉菜单, / p>

Update: For drop down menus, you want to change this:

<select name="foo">
  <option value="bar">Text</option>
</select>

使用 selected =selected

<select name="foo">
  <option value="bar" 
    <?php if(isset($_POST['foo']) && $_POST['foo'] == 'bar') 
          echo ' selected="selected"';
    ?>
  >Text</option>
</select>

注意保持上面显示的两个bar值同步(回显循环中的选项将有助于确保这一点)。

Be careful to keep the two "bar" values that appear above synchronized (echoing the options in a loop will help to make sure of that).