Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep form values after submit 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.

like image 632
shinjuo Avatar asked Apr 01 '11 14:04

shinjuo


2 Answers

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.

For example, if you currently have this:

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

You want to change it to this:

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

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

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

To this, which uses selected="selected":

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

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).

like image 158
Jon Avatar answered Sep 27 '22 22:09

Jon


You could do this:

<input name="cb" type="checkbox" <?php echo (isset($_POST['cb']) ? 'checked' : '') ?>>
like image 32
xil3 Avatar answered Sep 27 '22 21:09

xil3