How to reload current page without losing any form data?
JavascriptJqueryHtmlJquery UiJavascript Problem Overview
Can I reload current page without losing any form data? I used..
window.location = window.location.href;
and
window.location.reload(true);
But these two things can't get earlier form datas for me. What is wrong ? When refresh browser manually, it is fine (I don't lose any form data). Please guide me how to figure it out.
Here is my full code...
<div class="form-actions">
<form>
<table cellpadding = "5" cellspacing ="10">
<tr class="control-group">
<td style="width: 100px;">
<div>Name: <font color="red">(*)</font></div>
</td>
<td>
<input type="text" id="inputName" placeholder="Name" required>
</td>
</tr>
<tr class="control-group">
<td>
<div>Email: <font color="red">(*)</font></div>
</td>
<td>
<input class="span3" placeholder="[email protected]" id= "inputEmail" type="email" required>
</td>
</tr>
<tr class="control-group">
<td>
<div>Phone: </div>
</td>
<td>
<input type="text" id="inputPhone" placeholder="phone number">
</td>
</tr>
<tr class="control-group">
<td>
<div>Subject: <font color="red">(*)</font></div>
</td>
<td>
<input type="text" id="inputSubject" placeholder="Subject" required>
</td>
</tr>
<tr class="control-group">
<td colspan ="2">
<div>
<div>Detail: </div>
<div class="controls">
<textarea id="inputDetail"></textarea>
</div>
</td>
</tr>
<tr>
<td colspan="2">
<div>
<label style="font-weight: bold;" class="checkbox"> <input id="confirmCheck" value="" type="checkbox">
I Agree to the Personal information handling policy
</label>
</div>
<div id = "alert_placeholder"></div>
<div class="acceptment">
[Personal information handling policy]<br> <br>
</div>
</td>
</tr>
<tr>
<td colspan="2">
<div align="center">
<button id="btnConfirm" class="btn btn-primary">Confirm</button>
<input type="reset" style="width: 65px; height: 27px;" id="btnReset" class="btn">
</div>
</td>
</tr>
</table>
</form>
</div>
And at my JS file..
function bind() {
$('#btnConfirm').click(function(e) {
if ($('#confirmCheck').is(":checked")) {
getConfirmationForSendFAQ();
}
else {
e.preventDefault();
showalert("You should accept \"Personal Information Policy\" !", "alert-error");
}
});};function getConfirmationForSendFAQ() {
var name = $('#inputName').val();
var email = $('#inputEmail').val();
var phone = $('#inputPhone').val();
var subject = $('#inputSubject').val();
var detail = $('#inputDetail').val();
$('.form-actions').empty();
html = [];
html.push("<table cellpadding ='8' class = 'submitInfo'");
html.push("<tr>");
html.push("<td class = 'title'>Name:</div>");
html.push("<td class = 'value'>"+ name +"</td>");
html.push("</tr>");
html.push("<tr>");
html.push("<td class = 'title'>Email Address:</div>");
html.push("<td class = 'value'>"+ email +"</td>");
html.push("</tr>");
if (phone.trim().length > 0) {
html.push("<tr>");
html.push("<td class = 'title'>Phone No:</div>");
html.push("<td class = 'value'>"+ phone +"</td>");
html.push("</tr>");
}
html.push("<tr>");
html.push("<td class = 'title'>Subject:</div>");
html.push("<td class = 'value'>"+ subject +"</td>");
html.push("</tr>");
html.push("<tr>");
html.push("<td class = 'title'>Detail Info:</div>");
html.push("<td class = 'value'>"+ detail +"</td>");
html.push("</tr>");
html.push("<tr>");
html.push("<td colspan='2'><div align = 'center'>");
html.push("<button id='btnSend' class='btn btn-primary' style='width: 65px;'>Send</button>");
html.push("<button id='btnReturn' class='btn btn-inverse' style='width: 65px; height: 27px; margin-left: 5px;'>Return</button>");
html.push("</div></td></tr>");
html.push("</table>");
$('.form-actions').append(html.join(''));
$('#btnReturn').click(function(e) {
// HERE I WANT TO KNOW HOW TO DO.....
});
$('#btnSend').click(function(e) {
alert("Doom");
});}
Javascript Solutions
Solution 1 - Javascript
You can use various local storage mechanisms to store this data in the browser such as Web Storage, IndexedDB, WebSQL (deprecated) and File API (deprecated and only available in Chrome) (and UserData with IE).
The simplest and most widely supported is WebStorage where you have persistent storage (localStorage
) or session based (sessionStorage
) which is in memory until you close the browser. Both share the same API.
You can for example (simplified) do something like this when the page is about to reload:
window.onbeforeunload = function() {
localStorage.setItem("name", $('#inputName').val());
localStorage.setItem("email", $('#inputEmail').val());
localStorage.setItem("phone", $('#inputPhone').val());
localStorage.setItem("subject", $('#inputSubject').val());
localStorage.setItem("detail", $('#inputDetail').val());
// ...
}
Web Storage works synchronously so this may work here. Optionally you can store the data for each blur event on the elements where the data is entered.
At page load you can check:
window.onload = function() {
var name = localStorage.getItem("name");
if (name !== null) $('#inputName').val("name");
// ...
}
getItem
returns null
if the data does not exist.
Use sessionStorage
instead of localStorage
if you want to store only temporary.
Solution 2 - Javascript
I modified K3N's code to work for my purpose, and I added some comments to help others figure out how sessionStorage works.
<script>
// Run on page load
window.onload = function() {
// If sessionStorage is storing default values (ex. name), exit the function and do not restore data
if (sessionStorage.getItem('name') == "name") {
return;
}
// If values are not blank, restore them to the fields
var name = sessionStorage.getItem('name');
if (name !== null) $('#inputName').val(name);
var email = sessionStorage.getItem('email');
if (email !== null) $('#inputEmail').val(email);
var subject= sessionStorage.getItem('subject');
if (subject!== null) $('#inputSubject').val(subject);
var message= sessionStorage.getItem('message');
if (message!== null) $('#inputMessage').val(message);
}
// Before refreshing the page, save the form data to sessionStorage
window.onbeforeunload = function() {
sessionStorage.setItem("name", $('#inputName').val());
sessionStorage.setItem("email", $('#inputEmail').val());
sessionStorage.setItem("subject", $('#inputSubject').val());
sessionStorage.setItem("message", $('#inputMessage').val());
}
</script>
Solution 3 - Javascript
Find this on GitHub. Specially created for it.
Solution 4 - Javascript
This answer was extremely helpful to me, and saves the trouble of going through each field manually:
https://stackoverflow.com/questions/3432614/using-jquery-to-store-the-state-of-a-complicated-form
Solution 5 - Javascript
window.location.reload() // without passing true as argument
works for me.
Solution 6 - Javascript
As some answers mention, localStorage is a good option and you can certainly do it yourself, but if you're looking for a polished option, there is already a project on GitHub that does this called garlic.js.
Solution 7 - Javascript
I usually submit automatically my own form to the server and reload the page with filled arguments. Replace the placeholder arguments with the params your server received.
Solution 8 - Javascript
Agree with HTML5 LocaStorage. This is example code
Solution 9 - Javascript
You have to submit data and reload page (server side render form with data), just reloading will not preserve data. It is just your browser might be caching form data on manual refresh (not same across browsers).
Solution 10 - Javascript
You can use localStorage ( http://www.w3schools.com/html/html5_webstorage.asp ) to save values before refreshing the page.
Solution 11 - Javascript
You can use a library I wrote, FormPersistence.js which handles form (de)serialization by saving values to local/session storage. This approach is similar to that linked in another answer but it does not require jQuery and does not save plaintext passwords to web storage.
let myForm = document.getElementById('my-form')
FormPersistence.persist(myForm, true)
The optional second parameter of each FormPersistence
function defines whether to use local storage (false
) or session storage (true
). In your case, session storage is likely more appropriate.
The form data by default will be cleared from storage upon submission, unless you pass false
as the third parameter. If you have special value handling functions (such as inserting an element) then you can pass those as the fourth parameter. See the repository for complete documentation.
Solution 12 - Javascript
A simple and generic (no jquery) solution for all input (type text) fields unsing the local storage.
function save_data(){
let fields = document.querySelectorAll("input[type='text']")
let saved_fields = []
fields.forEach(x => {
saved_fields.push({
key: x.id,
value: x.value
})
})
localStorage.setItem("saved_data", JSON.stringify(saved_fields))
}
function show_saved_data(){
JSON.parse(localStorage.getItem("saved_data")).forEach(x => {
document.getElementById(x.key).value = x.value
})
}
if you want to include "select/checkboxes" fields etc. you would have to add some if else logic in the for loop and change the query....
Solution 13 - Javascript
Use $_POST itself:
<?php
isset($_POST['value']) ? $value= $_POST['value'] : $value= NULL;
echo '<form method="POST">';
echo '<input type="text" name="value" value="'.$value.'"/>';
echo '<input type="submit" name="submit" value="Submit"/>';
echo '</form>';
?>
Solution 14 - Javascript
Register an event listener for keyup
event:
document.getElementById("input").addEventListener("keyup", function(e){
var someVarName = input.value;
sessionStorage.setItem("someVarKey", someVarName);
input.value = sessionStorage.getItem("someVarKey");
});