Page 1 of 1
Radio Button
Posted: Wed Sep 26, 2007 12:03 am
by z0
Code: Select all
<input name="male" type="radio" value="male"> Male
<input name="female" type="radio" value="female"> Female
In the above code,both the radio buttons are getting selected!!
How to make sure that only one radio button can be selected?
I mean without javascript.

Also,I want to ensure that only one button is selected initially by default.But when I click the other button,the default button gets de-selected.
How to do that?
Is it possible without invoking javascript?(Bcz,I dont know javascript!!!

)
Posted: Wed Sep 26, 2007 12:13 am
by aaronhall
The name fields should be the same, something like "gender", or else they're treated as two separate radio lists.
edit: The default for a radio can be set using the checked attr:
Code: Select all
<input type="radio" name="gender" value="male" checked="checked" />
Posted: Wed Sep 26, 2007 12:14 am
by Hemlata
Hello,
To select one among multiple radio buttons, you need to set there
'name' attribute
same ie. eg. make name=''gender' for both the radio buttons and check the results. and to get default selected value, provide the attribute '
checked'.
Code: Select all
<input name="gender" type="radio" value="male" checked> Male
<input name="gender" type="radio" value="female"> Female
Hope you will get the required results
Regards,
re:radio buttons
Posted: Wed Sep 26, 2007 1:20 am
by z0
Yes,I have done as you have said.Default checked is 'Male'.
But when I select 'Female',after that it the output is always coming as 'Female" !!!
My re-written code is:
Code: Select all
<input name="gender" type="radio" value="male" checked="checked"> Male
<input name="gender" type="radio" value="female"> Female
<input name="sub" type="submit" value="Submit">
</form>
<?php
if(isset($_POST[gender]))
{
$gender="Male";
}
if(isset($_POST[gender]))
{
$gender="Female";
}
echo "<br>";
echo "I am " . $gender;
}
?>
</body>
</html>
The output page now is always showing :-
"I am Female"
even when default "male" is selected !!!

Posted: Wed Sep 26, 2007 1:33 am
by Hemlata
Hello,
That is because of your if block conditions which were always executing both the blocks as $_POST['gender'] is always set and the php variable $gender is always having the final value set as 'Female'. Modify that patch with the following to get the required results.
Code: Select all
<?php
if(isset($_POST['gender']))
{
$gender=$_POST['gender'];
}
echo "<br>";
echo "I am " . $gender;
?>
Hope this will solve your issue
Regards,