2017-08-09 39 views
0

晚上好,我有一個問題,我正在找人幫我。通過php發送頁面後保存select的值

我有以下問題,我生成一個select與所有選項來自數據庫,我通過一個後置動作,使用PHP發送信息。

我希望當返回到頁面時,使用select選項後,最後一個選定的值被激活到窗體。是否有可能通過JavaScript或其他方式做到這一點?

*對不起,我英文不好

$sql = "SELECT * FROM curso WHERE data = '$date'"; 
    $result = mysql_query($sql, $conexao2); 

    echo "<select name=\"curso\" >"; 

    while($linha = mysql_fetch_row($result)) { 
     $nome_evento = $linha[1]; 
     $cod_evento = $linha[0]; 
     echo "<option value=".$cod_evento.">".$nome_evento."</option>"."<br>" ; 
    } 
    echo "</select>"; 
+1

你好順便說一句。你是否正在試圖將選擇框設置爲上一個選定的項目。

+0

你需要做的是獲得該選定的值,並將其作爲變量傳入,然後在循環中檢查並設置「selected」值到那個匹配當前所在的那個,請參見下面的 –

+0

mysql_ *函數已被棄用,您需要使用mysqli或PDO。 – Enstage

回答

0

OK,你還需要得到先前輸入以及價值。

$sql = "SELECT * FROM curso WHERE data = '$date'"; 
$result = mysql_query($sql, $conexao2); 

$currentlySelectedValue = ///Add your code here to get this value 

echo "<select name=\"curso\" >"; 

while($linha = mysql_fetch_row($result)) { 
    $nome_evento = $linha[1]; 
    $cod_evento = $linha[0]; 
    echo '<option value=' . $cod_evento . ' ' . (($cod_evento === $currentlySelectedValue) ? 'selected' : '') . '>' . $nome_evento . '</option>'; 
} 
echo "</select>"; 

那麼中option地區正在發生的事情是:

(($cod_evento === $currentlySelectedValue) ? 'selected' : '')

是檢查與您輸出值選擇的值,如果一個相匹配,它會再加入selected的價值。

希望這有助於反正。

+0

我現在要測試,非常感謝。 –

+0

我不會在這裏待幾個小時,但希望你有一個開始,如果其附近的其他人可以幫助,謝謝 –

+0

謝謝,工作正常,感謝您的時間丟失kkk。 –

0

@Anderson Augusto有可能通過javascript或其他方式做到這一點?

是的,你可以通過Ajax接近它無需重新加載頁面

1)創建ajax.php裏面你有這樣的

<?php 
class Curso { 

    // Print select option value as soon as page load 
     public function curso($date){ 

$sql = "SELECT * FROM curso WHERE data = '$date'"; 
    $result = mysqli_query($sql, $conexao2); 
    while($linha = mysqli_fetch_row($result)) { 
     $nome_evento = $linha[1]; 
     $cod_evento = $linha[0]; 
     return ("<option value=".$cod_evento.">".$nome_evento."</option>"); 
    } 


     } 
} 

?> 

2)創建frontpage.php裏面的你有這個

<!doctype html> 
    <html> 
    <head> 
    <meta charset="utf-8"> 
    <title>My front page</title> 
    </head> 

    <body> 
    <form id="CursoForm"> 
    <?php 
    require("ajax.php"); 
    $OptionValues= new Curso(); 
    $TheValues =$OptionValues->curso("YOUR-DATE"); 
    ?> 
    <!--Maybe some other inputs--> 
    <input type="text"> 
    <select name="curso"><?php echo($TheValues);?></select> 
    </form> 

    <script> 
//================================== 
$("form#CursoForm").on("submit",function(event) { 
event.preventDefault(); 
$.ajax({ 
type: "POST", 
url: "path/to/your/further/function.php", 
cache: false, 
dataType: 'html',//choose what you are expecting e.g. JSON | HTML | TEXT 
data: $(this).serialize(), 
success: function(data){  
//handle do something with re 
}, 
error: function(){  
//handle do something wth the error 
} 
}); 
}); 
// 
</script> 
    </body> 
    </html> 
+0

謝謝您花時間,但我已經解決了這個問題,非常感謝。 –