Search code examples
phpradio-buttonundefinedforum

Undefined Variable when trying to make a radio button sticky


Here is my code:

$isYes = FALSE;
$isNo = FALSE;
if (!empty($_POST['owner'])) {
 $o = trim($_POST['owner']);
 if ($_POST['owner'] == 'yes') {
     $isYes = TRUE;
 } else if($_POST['owner'] == 'no'){
     $isNo = TRUE;
     }
 }

<p><label>Is the Applicant the owner? &nbsp;&nbsp;
Yes<input type="radio" name="owner" id="owner_yes" class="owner" value="yes" 
<?php print($isYes ? "CHECKED" : ""); ?> />
No<input type="radio" name="owner" id="owner_no" class="owner" value="no" 
<?php print($isNo ? "CHECKED" : ""); ?>/></label></p>

Whenever the user first loads up the page, it gives this error:

Notice:** Undefined variable: isYes in C:\xampp\htdocs\index.php on line 299
Notice:** Undefined variable: isNo in C:\xampp\htdocs\index.php on line 301

That is because the user has not selected "yes" or "no" in the radio filled above yet, but after they hit submit and come back to fix what they may have messed up, the error(s) go away because $isYes and $isNo now have a value.

How can I fix this error? Thanks in advance guys!


Solution

  • I figured it out. I had to do this:

    if (isset($_POST['owner'])) { print($isNo ? "CHECKED" : ""); }
    

    I had to check if the variable was set, and if it was, then set the value.