簡體   English   中英

表單提交后保留輸入值(帶有捕獲)

[英]Keep input value after form submit (with a catch)

在PHP中,如果文本輸入“ cmtx_comment”為空,則在表單提交時會顯示一個JavaScript警報。 在警報中按“確定”后,用戶在表單中所有字段中輸入的值都消失了。 如何在不向輸入元素的值添加代碼的情況下保持用戶輸入的值 (類似於<input type="text" name="something" value="<?php echo $_GET['something'];?>">

if (empty($cmtx_comment)) { //if comment value is empty
echo <<<EOD
<script>
alert('Please enter a comment!');
</script>
EOD;
return false;
} else { //if comment entered
do stuff

您是否嘗試過localStorage和表單驗證?

HTML:

<form method="post" action="" onSubmit="return saveComment();">
    <input type="text" name="cmtx_comment" id="cmtx_comment" value="" />
    <input type="submit" value="Save" />
</form>

JavaScript:

document.getElementById("cmtx_comment").value = localStorage.getItem("comment");

function saveComment() {
    var comment = document.getElementById("cmtx_comment").value;
    if (comment == "") {
        alert("Please enter a comment in first!");
        return false;
    }

    localStorage.setItem("comment", comment);
    alert("Your comment has been saved!");

    location.reload();
    return false;
    //return true;
}

在首頁加載時,您將看到:

如果您不輸入評論,則會收到警報:

如果輸入注釋,你會得到一個不同的警報:

然后頁面將刷新(或發布,只需取消注釋返回的true,並注釋location.reload),您仍會看到第一次發布的內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM