提交PHP后保持表格形式的价值 [英] Keep value in form after submitting PHP
问题描述
我正在从控制器中调用这些函数以获取表单和表单中的值.我的问题是,提交失败后如何将值保留在表单中?我已经尝试过这样的事情:
I'm calling these functions from a controller to get the form and the values from the form. My question is, how can I keep the values in the form after a submit fails? I've tried something like this:
<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;
}
推荐答案
[edit: run this on localhost]
autocomplete
并非在所有浏览器上都有效;此外,它仅是一个提示,因此cookie是剩下的唯一选项.下面的解决方案效果很好,但是如果其他用户对此受欢迎的请求提供其他方式: Keep value in form after submitting
.
autocomplete
does not work on all browsers; moreover, it is only a hint, so cookies are the only option left. The solution below works fine, however it will be great if other users contribute alternate ways for this popular request : 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>
这篇关于提交PHP后保持表格形式的价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!