2017-03-01 51 views
0

我試圖存儲一個單選按鈕的輸入值並將其存儲到一個會話中,以便如果用戶在站點周圍漫遊,則無線電保持選中狀態,除非他們自己切換它,然後新的選擇仍然被檢查。設置一個單選按鈕進入會話保留選中狀態

<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; 
} 
?> 

我似乎無法得到它保持在選中狀態......

+1

我想!你應該在html之前編寫你的php代碼。 – Akshay

+0

它的作品,但當你移動到另一個頁面,它會回到它的原始狀態 – PhpDude

+0

我希望你不會發布任何值'reportType'從另一個頁面 – Akshay

回答

1

檢查這個代碼

<?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> 
+0

這不保留狀態 – PhpDude

+0

檢查我的更新代碼 –

+0

嗯,這樣做不保持它像你以前的代碼示例一樣檢查 – PhpDude

1

放入會議的價值和使用會話變量來填充值在單選按鈕代替使用額外的變量。

通過從會話填充它將有助於保留在所有頁面中。

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

當你移動頁面到頁面時,它不會保持它的狀態嗎? – PhpDude

+0

在其他頁面中,你沒有獲得價值可以做print_r($ _ SESSION),看到值是否存在....我希望你不會錯過session_start() – Naincy