Radio Button Query

Soldato
Joined
18 Oct 2002
Posts
4,656
Location
The Darkside
I'm not sure whether I am being stupid or what but I have a page and a section of it contains 3 radio buttons. I use these radio buttons so the user selects one of the 3 choices.

Now I am creating an update/edit form with the records details being retrieved from a database via php. How does one get the radio button that matches the record on file to be set active and shown to be on the form.

Atm, the radio buttons are blank but I would like one to be marked corresponding to whatever option was selected when the record was first inputted. I have looked deep into the net but cannot find reference to setting a radio button active depending on the value of a variable.

Its easy to set the variable from the radio button value but not vice versa.

Can this be done?

Reason for this is to allow the user to make a different choice if the original selection was wrong.
 
use checked="checked" to set a default. eg

PHP:
<input type="radio" name="sex" checked="checked" value="male"> Male
<input type="radio" name="sex" value="female"> Female

now you just need to implement this in your php to output checked="checked" in the right place.

i'd store the values in an array, loop through it and check if each value matches my db record - and output checked="checked" if it does....

PHP:
$default = //record from db
$values = array('male', 'female');
foreach($values as $value) {
   echo '<input type="radio" name="sex"';
   if($value == $default) echo ' checked="checked"';
   echo ' value="' . $value . '"> ' . ucfirst($value);
}
 
Last edited:
Back
Top Bottom