PhpDude PhpDude -4 years ago 124
PHP Question

Setting a radio button into session to retain checked state

I am trying to store the input value of a radio button and storing that intoa session so that if the user roams around the site the radio remains checked unless they switch it themselves and then the new selection remains checked.

<form action="" method="POST" id="reportSwitch">
<input checked type="radio" name="reportType" id="leadership" value="1" <?php if($reportType == 1){
echo 'checked';} ?>>
<label for="leadership">Leadership</label>
<input type="radio" name="reportType" id="fundementals" value="2" <?php if($reportType == 2){
echo 'checked';} ?>>
<label for="fundementals">Fundementals</label>
</form>


<?php
$_SESSION['reportType'] = $_POST['reportType'];
$reportType = $_SESSION['reportType'];

if(isset($reportType)){
} else{
$reportType = 1;
}
?>


I cannot seem to to get it to remain in a checked state...

Answer Source

check this code

<?php
session_start();
$_POST['reportType'] = 1; // for testing it is set define value , you can change 
if(isset($_POST['reportType'])){
 $_SESSION['reportType'] = $_POST['reportType'];
 $reportType = $_SESSION['reportType'];
} else {
 $reportType = $_SESSION['reportType'];
}

 if(!isset($reportType)){
 $reportType = 1;
 }
?>
<form action="" method="POST" id="reportSwitch">
<input checked type="radio" name="reportType" id="leadership" value="1" <?php if($reportType == 1){
    echo 'checked';} ?>>
<label for="leadership">Leadership</label>
<input type="radio" name="reportType" id="fundementals" value="2" <?php if($reportType == 2){
    echo 'checked';} ?>>
<label for="fundementals">Fundementals</label>
 </form>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download