receiving radio box value in php
Asked Answered
P

4

15

I have 2 following radio boxes in a form,

<input type="radio" name="radio" value="yes" class="radio" /> Yes
<input type="radio" name="radio" value="no" class="radio" /> No
  1. How can i recieve the value of the radio button once the form is posted (in PHP)
  2. Once it is posted on the same page, how can I remember the selected radio button and keep that checked? Thanks.
Pomeroy answered 2/3, 2011 at 12:41 Comment(0)
E
24

1) The value of the radio button is saved in $_POST only if any of the choices was selected.

if (isset($_POST['radio']))   // if ANY of the options was checked
  echo $_POST['radio'];    // echo the choice
else
  echo "nothing was selected.";

2) Just check for the value and add checked='checked' if it matches.

<input type="radio" name="radio" value="yes" class="radio" <?php if (isset($_POST['radio']) && $_POST['radio'] == 'yes'): ?>checked='checked'<?php endif; ?> /> Yes
<input type="radio" name="radio" value="no"  class="radio" <?php if (isset($_POST['radio']) && $_POST['radio'] ==  'no'): ?>checked='checked'<?php endif; ?> /> No
Elector answered 2/3, 2011 at 12:47 Comment(0)
G
5
<input type="radio" name="radio" value="yes" class="radio" /> Yes
<input type="radio" name="radio" value="no" class="radio" /> No

 u get radio value using $_POST['radio'];

simple bro,

<input type="radio" name="radio" <?php if($_POST['radio']=="yes") echo "checked";?> value="yes" class="radio" /> Yes

u have to identify radio box by value man

Gush answered 2/3, 2011 at 13:9 Comment(0)
V
2

How can i recieve the value of the radio button once the form is posted (in PHP)

$_POST['radio']

Once it is posted on the same page, how can I remember the selected radio button and keep that checked?

Add a checked attribute if the value is equal to $_POST['radio'].

Vaudevillian answered 2/3, 2011 at 12:43 Comment(0)
P
2

1) u will receive only that radio box value via POST which is checked

    $radio_value=$_POST['radio'];

2)

<input type="radio" name="radio" value="yes" class="radio" 
   <?php echo ($radio_value == 'yes') ? 'checked="checked"' : ''; ?>/> Yes
<input type="radio" name="radio" value="no" class="radio" 
   <?php echo ($radio_value == 'no') ? 'checked="checked"' : ''; ?>/> No
Puttergill answered 2/3, 2011 at 12:47 Comment(4)
there should be errors/mistake on your code. Please correct me :)Improvisation
@Improvisation would you please like to mention the error/mistake/typo, and of course go ahead to fix it :)Puttergill
<?php echo ($radio_value == 'yes') ?> - you closed the PHP tag, and then you use the PHP Short IF statement?Improvisation
@Improvisation thanks for pointing. I corrected it and btw its a ternary operator.Puttergill

© 2022 - 2024 — McMap. All rights reserved.