faqts : Computers : Programming : Languages : PHP : Common Problems : Forms and User Input

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

165 of 237 people (70%) answered Yes
Recently 5 of 10 people (50%) answered Yes

Entry

How to check which radio button is checked and pass the name of the radio button as argument?
how to check an array of radiobuttons in Javascript

Mar 24th, 2001 12:48
Mike Mannakee, Narendra Jain, Naveen Ghanathe, Ben Udall, Muruga boopathy,


Make sure that the input tag has a name attached to each radio button.
You may default one of these radio buttons by giving it a 'checked'
property. Then, when the submit button for the form is pressed, check
for the name to be true / 1. 
The input is done as:
<form action="check_sex.phtml" method="post">
<input type="radio" name="male" value="male" checked>Male
<br>
<input type="radio" name="female" value="female" checked>Female
<br>
<input type="submit" value="Select Sex">
</form>
Then in check_sex.phtml have the code as:
<?
if ($female == 1) { echo "Female Selected"; }
elseif ($male ==1) { echo "Male Selected"; }
?>
**************  CORRECTION  *****************
I felt I had to put this in when I read the above answer:
Actually, this should be done by naming the two radio buttons with the 
same name, thus only one can be checked at a time. Like:
<form action="check_sex.php">
<input type="radio" name="sex" value="male">Male<br>
<input type="radio" name="sex" value="female">Female<br>
<input type="submit" value="Select Sex"><br>
</form>
Otherwise, as in the above answer, you could (and would) have both 
buttons checked at the same time, and the code :
<?
if ($female == 1) { echo "Female Selected"; }
elseif ($male ==1) { echo "Male Selected"; }
?>
would have to be changed to:
<?
if ($female == "female") { echo "Female Selected"; }
elseif ($male == "male") { echo "Male Selected"; }
?>
to even work.  Remember, the HTML assigned values of "male" 
and "female", not "1".
So that code will always produce:
Female Selected.
Not what you'd want. For half the users, anyways.  Radio buttons are 
associated with each other by name only.  If you wanted only one of a 
group selected at one time they must share the name.  Then code the 
script like this:
<?
if ($sex=="male") echo "Male Selected";
elseif($sex=="female") echo "Female Selected";
elseif(!$sex) echo "Neither Selected";
?>
and you've got every possibility covered, including the user not 
checking anything.