我从控制器调用这些函数来获取表单中的表单和值。我的问题是,如何在提交失败后将值保留在表单中?我尝试过这样的事情:
<input type="text" name="myField1" value="<?php echo isset($_POST['myField1']) ? $_POST['myField1'] : '' ?>" />
但无法让它发挥作用。
private $m_username = 'username';
private $m_password = 'password';
private $m_registerButton = 'registerButton';
public function RegisterUserBox(){
return
'<form method="post">
<fieldset>
Username: <input type="text" name="'.$this->m_username.'" />
Password: <input type="password" name="'.$this->m_password.'" />
<input type="submit" value="Register" name="'.$this->m_registerButton.'"/>
</fieldset>
</form>';
}
public function GetUsername(){
if(isset($_POST[$this->m_username])){
return $_POST[$this->m_username];
}
}
public function GetPassword(){
if (isset($_POST[$this->m_password])){
return $_POST[$this->m_password];
}
}
public function TriedToRegister(){
if (isset($_POST[$this->m_registerButton])){
return true;
}
return false;
}
答案 0 :(得分:1)
[edit: run this on localhost]
autocomplete
不适用于所有浏览器;此外,它只是一个提示,所以cookie是唯一的选择。下面的解决方案运行正常,但如果其他用户为此热门请求提供了其他方式,那就太棒了: Keep value in form after submitting
。
<html>
<head>
<script>
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
function store() {
var inputs, index;
inputs = document.getElementsByTagName('input');
for (index = 0; index < inputs.length - 1; ++index) {
setCookie(inputs[index].name,inputs[index].value,1);
}
return false;
}
</script>
</head>
<body>
<form method="post" action="back.php" onsubmit="store()" >
firstname<input type="text" name="firstname">
lastname<input type="text" name="lastname">
emailid<input type="text" name="emailid">
<input type="submit" >
</form>
<script>
(function load(){
var inputs, index;
inputs = document.getElementsByTagName('input');
for (index = 0; index < inputs.length - 1; ++index) {
inputs[index].value = getCookie(inputs[index].name);
}
return false;
})();
</script>
</body>
</html>
答案 1 :(得分:0)
<html>
<body>
<form method="post" action="back.php" autocomplete="on" >
<input type="text" autocomplete="on" >
<input type="submit" >
</form>
</body>
</html>
答案 2 :(得分:0)
在表单之前,实例化将接收$_POST
数据
$userbox = new Userbox;
然后处理$_POST
数据,如果有的话:
if(isset($_POST['submit']) && $_POST['submit'] === 'userboxsubmit'){
$userbox->process_post();
}
然后输出表格:
<input type="text" name="myField1" value="<?php echo $userbox->myField1; ?>" />