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 tr
Before your form, instantiate the object which will receive the $_POST
data
$userbox = new Userbox;
Then process $_POST
data, if there is any:
if(isset($_POST['submit']) && $_POST['submit'] === 'userboxsubmit'){
$userbox->process_post();
}
Then output the form:
<input type="text" name="myField1" value="<?php echo $userbox->myField1; ?>" />
[edit: run this on localhost]
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>
<html>
<body>
<form method="post" action="back.php" autocomplete="on" >
<input type="text" autocomplete="on" >
<input type="submit" >
</form>
</body>
</html>