How to retain value of a radio button

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
edawson003
Forum Contributor
Posts: 133
Joined: Thu Aug 20, 2009 6:34 am
Location: Los Angeles, CA - USA

How to retain value of a radio button

Post by edawson003 »

How can code a radio button such that it retains it's value (checked) after a unsuccessful form post?

Here's how setup a a text field to retain value. I figure for radios, it should be too far off.

Code: Select all

<input class=clp type="text" name="exname" maxlength="50" size="40" value="<?php echo isset($exname) ? $exname : ''; ?>" />

Code: Select all

<input type="radio" name="extype" value="1">
<input type="radio" name="extype" value="2">
<input type="radio" name="extype" value="3">
Last edited by edawson003 on Wed Oct 14, 2009 12:58 am, edited 1 time in total.
User avatar
Mirge
Forum Contributor
Posts: 298
Joined: Thu Sep 03, 2009 11:39 pm

Re: How to retain value of a radio button

Post by Mirge »

edawson003 wrote:How code a radio button such that it retains it's value (checked) after a unsuccessful form post?

Code: Select all

<input class=clp type="text" name="exname" maxlength="50" size="40" value="<?php echo isset($exname) ? $exname : ''; ?>" />

Code: Select all

<input type="radio" name="extype" value="1">
<input type="radio" name="extype" value="2">
<input type="radio" name="extype" value="3">
Well, one way would be to put an if() statement in each of the input radio's... for example (assuming form's method is POST):

Code: Select all

 
<input type="radio" name="extype" value="1"<?php if($_POST['extype'] == '1') { print "checked "; } ?>>
<input type="radio" name="extype" value="2"<?php if($_POST['extype'] == '2') { print "checked "; } ?>>
<input type="radio" name="extype" value="3"<?php if($_POST['extype'] == '3') { print "checked "; } ?>>
 
If you're using method="GET" instead, replace $_POST with $_GET.
User avatar
edawson003
Forum Contributor
Posts: 133
Joined: Thu Aug 20, 2009 6:34 am
Location: Los Angeles, CA - USA

Re: How to retain value of a radio button

Post by edawson003 »

works perfect! Thanks!
User avatar
Mirge
Forum Contributor
Posts: 298
Joined: Thu Sep 03, 2009 11:39 pm

Re: How to retain value of a radio button

Post by Mirge »

Not a problem. 8)
Post Reply