Forum Moderators: coopster

Message Too Old, No Replies

Passing $POST variable to radio button on form reload

         

WoodNotOil

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

10+ Year Member



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?

chrisranjana

5:31 pm on Feb 18, 2011 (gmt 0)

10+ Year Member



Here you go

[echoecho.com...]

The keyword is "checked"

rocknbil

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

WebmasterWorld Senior Member 10+ Year Member



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]

WoodNotOil

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

10+ Year Member



Thanks, just what I needed to know!