Page 1 of 1

persistent $_POST for radio buttons, checkboxes & selects

Posted: Fri Sep 10, 2010 2:47 pm
by seezee
I'm trying a new way of handling forms. In the past I've done validation 1st on the client side (JavaScript), then server side (PHP). The PHP that handled the form was on an external page. If $errors = true, the handler would display a list of errors & present a 'go back' button.

In an effort to make the form friendlier for people who have JS disabled, I've moved the PHP form handling to the same page as the form. I've figured out how to retain typed-in data in a text field by using something like this:

Code: Select all

<input type="text" name="foo" id="foo" value="<?php if(isset($_POST['submit'])){echo htmlentities($_POST['foo']) ?><?php } ?>" />
So that if a user submits the form and errors are displayed via PHP, the user doesn't have to re-enter all the form data. But how do I retain checked="checked" or selected="selected" states for radio buttons, checkboxes, and select inputs? I tried this guy's method, but it didn't work.

Thanks,

--cz

Re: persistent $_POST for radio buttons, checkboxes & select

Posted: Fri Sep 10, 2010 4:23 pm
by Christopher
You can either generate the select/radio-buttons/checkboxes with PHP and add the checked="checked" or selected="selected" as it loops through the options, OR you can have PHP insert some Javascript to do the check/select.

Re: persistent $_POST for radio buttons, checkboxes & select

Posted: Fri Sep 10, 2010 5:15 pm
by seezee
JavaScript is not an option; the server side checking asssumes JS failed, either because of skulduggery or because it's not available. But the following works (only tested on radio buttons, but should be good for other fields that post as an array):

Code: Select all

<?php if((isset($_POST['mySubmitAction'])) && ($_POST["foo"]=="fooValue")){echo "checked=\"checked\""; ?><?php } ?>
Just insert that in each radio button tag, replacing the 'mySubmitAction' with your submit button value & 'foo' w/ the radio button name; also replace fooValue w/ the radio button value.

Re: persistent $_POST for radio buttons, checkboxes & select

Posted: Fri Sep 10, 2010 10:58 pm
by John Cartwright
Your code assumes $_POST["foo"] will exist, which it is not guaranteed to. You should probably write it as:

Code: Select all

<?php if((isset($_POST['foo'])) && ($_POST["foo"]=="fooValue")){echo "checked=\"checked\""; ?><?php } ?>