Welcome to WebmasterWorld Guest from

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Passing $POST variable to radio button on form reload

4:46 pm on Feb 18, 2011 (gmt 0)

New User

5+ Year Member

joined:Mar 15, 2010
posts: 14
votes: 0

I have a form with radio buttons that pass a selected value through $POST['rating'] into a database. That part is working fine.

<label for "rating">*Service Rating:</label>
<input type="radio" name="rating" value="1" /> 1-Unsatisfactory
<input type="radio" name="rating" value="2" /> 2-Below Average
<input type="radio" name="rating" value="3" /> 3-Satisfactory
<input type="radio" name="rating" value="4" /> 4-Good
<input type="radio" name="rating" value="5" /> 5-Excellent</label>

What I need to do is have the posted value pre-selected if the user made an error and the form is reloaded. For the text fields I used:

value="<?php echo $_POST['email']; ?>"

And this fills the field if the form was posted and reloaded. How do you accomplish this with radio buttons?
5:31 pm on Feb 18, 2011 (gmt 0)

Junior Member from IN 

10+ Year Member

joined:Nov 3, 2002
posts: 91
votes: 0

Here you go


The keyword is "checked"
6:30 pm on Feb 18, 2011 (gmt 0)

Senior Member

WebmasterWorld Senior Member rocknbil is a WebmasterWorld Top Contributor of All Time 10+ Year Member

joined:Nov 28, 2004
votes: 0

Yes but for XHTML it's checked="checked", and to make that remotely useful, without a ton of spaghetti code, you'd need something like this. Many PHP coders would use form arrays, but this will work. :-)

$svc_ratings = get_svc_radios();

Then put "$svc_ratings" in your form, Or you could simply do

<?php echo get_svc_radios(); ?>

wherever you need it.

That function would look something like this.

function get_svc_radios() {
$radios="<strong>*Service Rating:</strong>";
$ratings = Array(
1 => '1-Unsatisfactory',
2 => '2-Below Average',
3 => '3-Satisfactory',
4 => '4-Good',
5 => '5-Excellent',
foreach ($ratings as $key => $value) {
// Note the *proper* application of labels here, assigned to ID
$id = 'rating_' . $key;
$radios .= "<input type=\"radio\" name=\"rating\" id=\"$id\" value=\"$key\"";
if (isset($_POST['rating']) and ($_POST['rating']==$key)) { $radios .= ' checked'; }
$radios .= "> <label for=\"$id\">$value</label>";
// Or ' checked="checked" if you *really need* a valid XHTML doctype.
// Which most people don't.
return $radios;

Typed on the fly, may contain errors.

Technically speaking, radios should always have one default button checked, I'd suggest adding one, "No Rating Provided" and making it the default, but most publishers ignore this advice. We do what we can do.

[edited by: rocknbil at 6:34 pm (utc) on Feb 18, 2011]

6:33 pm on Feb 18, 2011 (gmt 0)

New User

5+ Year Member

joined:Mar 15, 2010
posts: 14
votes: 0

Thanks, just what I needed to know!

Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members