How to Interact with Web Forms. Part 1 | 4

How to Interact with Web Forms. Part 1

Preselecting Radio Buttons

A group of radio buttons is identified by the common name attribute. Out of a group of buttons, only one can be selected (or none).When submitting a form to the server, the value attribute of the selected radio buttons is transmitted to the server.Therefore, it is quite messy but rather trivial to prefill a group of radio buttons: Just compare the value in $_GET/$_POST with the associated value. If it fits, print out checked, the HTML attribute that preselects a radio button, as shown in the code.

This code can be extended so that a radio button is preselected when the user has previously saved his selection in a cookie, using the include file getFormData.inc.php, as shown in the following code.

Preselecting Check Boxes

Although some websites pretend to group check boxes like radio buttons, this is technically not true. Every check box stands on its own; therefore, they all should have different names (it would not make sense to give them identical names).Then each check box can be treated individually: Check for the associated value attribute and print out the checked HTML attribute, if there is a match.

When using cookie data (if available), the code changes slightly.

Preselecting Selection Lists

On a single selection list, the value of the selected <option> element is transferred to the server when submitting the form.This value can then be manually checked to prefill the form, using the selected HTML attribute, as shown in the code.

The same effect can be implemented using getFormData.inc.php; then data from the site’s cookies is used, if available.

Next week, we begin with a look at Preselecting MultipleSelection Lists, Processing Graphical Submit Buttons, Checking Mandatory Fields and more.

Excerpted from Chapter 4: Interact with Web Forms from the PHP Phrasebook by Christian Wenz. ISBN 0672328178, Copyright © 2005. Used with the permission of Sams Publishing.

Created: March 27, 2003
Revised: January 16, 2006

URL: http://webreference.com/programming/php_forms/1