[英]Keep input value after form submit (with a catch)
In PHP, if the text input "cmtx_comment" is empty, on form submit I show a javascript alert. 在PHP中,如果文本输入“ cmtx_comment”为空,则在表单提交时会显示一个JavaScript警报。 After I press OK in the alert, the values entered by the user in all fields in the form are gone.
在警报中按“确定”后,用户在表单中所有字段中输入的值都消失了。 How can I keep the user entered values, without adding code to the value of the input elements (something like
<input type="text" name="something" value="<?php echo $_GET['something'];?>">
? 如何在不向输入元素的值添加代码的情况下保持用户输入的值 (类似于
<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
Have you tried localStorage and form validation? 您是否尝试过localStorage和表单验证?
HTML: 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: 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;
}
On first page load, you are presented with: 在首页加载时,您将看到:
If you don't enter a comment, you get the alert: 如果您不输入评论,则会收到警报:
If you do enter a comment, you get a different alert: 如果你输入注释,你会得到一个不同的警报:
The page will then refresh (or post, simply un-comment the return true, and comment the location.reload), and you will still see the contents you posted the first time. 然后页面将刷新(或发布,只需取消注释返回的true,并注释location.reload),您仍会看到第一次发布的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.