PHP: Automaticly select/check users submited info in form

Small, short code snippets that other people may find useful. Do you have a good regex that you would like to share? Share it! Even better, the code can be commented on, and improved.

Moderator: General Moderators

Post Reply
User avatar
JAM
DevNet Resident
Posts: 2101
Joined: Fri Aug 08, 2003 6:53 pm
Location: Sweden
Contact:

PHP: Automaticly select/check users submited info in form

Post by JAM »

Recently, forum users has asked about making checkboxes/radio/select elements in forms automaticly selected after the form is submited.
So I thought it would be in order to post a brief demonstration to help guiding those in the future.

Note: It can be written shorter, but I tried aiming at understanding it rather than saving bytes.

Code: Select all

<pre> <!-- I use the pre tag to make it easy to read -->
<?php
    if (!empty($_POST['foo'])) {    // check if the $_POST['foo'] was sendt.
        print_r($_POST);            // display debugging information.
        $variable = $_POST['foo'];  // add the sendt value to a variable
    } else {
        $variable = '';             // ...but mark it blank if it was not sendt at all.
    }
?>
<form method="post">
<input type="radio" name="foo" value="1" <?php echo ($variable == 1 ? 'CHECKED ' : ''); ?>/>1
<input type="radio" name="foo" value="2" <?php echo ($variable == 2 ? 'CHECKED ' : ''); ?>/>2
<input type="radio" name="foo" value="bar" <?php echo ($variable == 'bar' ? 'CHECKED ' : ''); ?>/>bar
<input type="submit" />
</form>
Result:
Image

Hope I gave answers to some questions.

Note: Im using alternative if-then-else syntax above, described here: viewtopic.php?t=14331
Post Reply