在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;
}
在首页加载时,您将看到:
如果您不输入评论,则会收到警报:
如果您确实输入了评论,则会收到其他警报:
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.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句