Categories
PHP

Preselecting Radio Buttons

When submitting a form to the server, the value of the selected radio button is passed to the server. Compare that value, if it fits, print out “checked” to preselect that radio button.

Radio buttons come in groups identified by using the same name attribute on all buttons within that group. A user can only select one radio button from a group of radio buttons. When a radio button is selected, any other radio button with the same name (in the group) that was previously selected becomes unchecked.

The checked attribute

Use the checked attribute to pre-select a radio button, for example:

checked
or
checked=""
or
checked="checked"

Each of these is a valid technique to define a checked radio button.

Example: pre-checked a radio button:

The last radio button (Blue) will be checked:

<input type="radio" name="color" value="Red"> Red
<input type="radio" name="color" value="Green"> Green
<input checked type="radio" name="color" value="Blue"> Blue

PHP – Preselecting Radio Buttons

<?php
 if (isset($_POST['groupname']) &&
  $_POST['groupname'] == 'any value') {
   echo 'checked';
 }

When processing a form in PHP, it is quite messy but rather trivial to prefill a group of radio buttons: Just compare the value in $_GET/$_POST with the associated value. If it fits, print out checked to preselect that radio button, as shown in the code:

<?php
 $color = htmlspecialchars ($_POST['color'] ?? ''); 
?>
<form method="post" action="example.php">
 <p>Radio Buttons:<br>
  <label>
<input type="radio" name="color" value="Red"
 <?= $color == 'Red' ? 'checked' : '' ?>>Red
  </label>
  <label>
<input type="radio" name="color" value="Blue"
 <?= $color == 'Blue' ? 'checked' : '' ?>>Blue
  </label>
  <label>
<input type="radio" name="color" value="Green"
 <?= $color == 'Green' ? 'checked' : '' ?>>Green
  </label>
 </p>
 <p><input type="submit" name="submit" value="Submit"></p>
</form>

Using a cookie to check the radio button

This code can be extended so that a radio button is preselected when the user has previously saved his selection in a cookie:

<?php
 if (isset($_POST['submit'])) {
  $color = htmlspecialchars ($_POST['color'] ?? '');
  
  // Save the form data in cookies when form is submitted
  setcookie('color', $color, strtotime ('+30 days'));
 }
 else {
  // Form not submitted
  // Retrieve data from cookies (if exist)
  $color = $_COOKIE['color'] ?? '';
 }
 
?>
<form method="post" action="example.php">
 <p>Radio Buttons:<br>
  <label>
   <input type="radio" name="color" value="Red"
    <?= $color == 'Red' ? 'checked' : '' ?>>Red
  </label>
  <label>
   <input type="radio" name="color" value="Blue"
    <?= $color == 'Blue' ? 'checked' : '' ?>>Blue
  </label>
  <label>
   <input type="radio" name="color" value="Green"
    <?= $color == 'Green' ? 'checked' : '' ?>>Green
  </label>
 </p>
 <p><input type="submit" name="submit" value="Submit"></p>
</form>

Processing Forms in PHP: