javascript 表单提交后保留输入值(带捕获)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26008538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Keep input value after form submit (with a catch)
提问by Malasorte
In PHP, if the text input "cmtx_comment" is empty, on form submit I show a javascript alert. 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'];?>">
?
在 PHP 中,如果文本输入“cmtx_comment”为空,则在表单提交时我会显示一个 javascript 警报。在警报中按 OK 后,用户在表单中所有字段中输入的值都消失了。如何在不向输入元素的值中添加代码的情况下保留用户输入的值(类似于<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
回答by Dave Chen
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 doenter 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.
然后页面将刷新(或发布,只需取消对 return true 的评论,并评论 location.reload),您仍将看到第一次发布的内容。