Skip to content
Advertisement

How to check or uncheck the radio button according to value in php?

I am stuck on the issue. I have two radio buttons. One is a Buyer and the second is the Seller.

 <input type="radio" name="account_type" value="1" id="acc_buyer" checked="checked">Buyer
 <input type="radio" name="account_type" value="2" id="acc_seller">Seller

The Buyer radio button is already checked.

Now What I am doing is, I have the below code, and if the $account_type==2 then I have to select the seller radio button and unchecked the buyer.

I tried the below code

 if(isset($_SESSION['error'])){
    $error = $_SESSION['error'];
    $account_type = $_SESSION['account_type'];
    unset($_SESSION['account_type']);
    unset($_SESSION['error']);
}
 
 <input type="radio" name="account_type" value="1" id="acc_buyer" checked="checked"> Buyer
 <input type="radio" name="account_type" value="2" id="acc_seller" <?php if(isset($account_type) && $account_type=='2') { ?> checked="checked" <?php }?>> Seller

Advertisement

Answer

Here’s the correction with the added empty() check.

$checked = [];
$checked[0] = empty($account_type) || (isset($account_type) && $account_type == 1) ? 'checked' : '';
$checked[1] = isset($account_type) && $account_type == 2 ? 'checked' : '';

<input type="radio" name="account_type" value="1" id="acc_buyer" checked="<?php echo $checked[0] ?>">
<input type="radio" name="account_type" value="2" id="acc_seller" checked="<?php echo $checked[1] ?>">
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement