I have an div that is shown when a form is submitted, but when I refresh the page, my data disappears and I'm searching for a way to preserve my data on page refresh.
I know how to save data in a session, but not an entire form. How do I approach this issue? Is it even possible to save an entire form with Javascript?
function showHide() {
var div = document.getElementById("hidden_form");
if (div.style.display == 'none') {
div.style.display = '';
} else {
div.style.display = 'none';
}
}
<form name="product_form" id="product_form" enctype="multipart/form-data" action="admin_products.php" method="post" accept-charset="utf-8" onsubmit="showHide();
return false;">
<input type="textfield" id="title" name="title" value="" readonly>
<div id='hidden_form' style="display:none">
<input type="text" id="name" name="name" value="" placeholder="Product Name">
<label id="option_1" name="option_1">Option Name</label>
<input type="text" id="optionn" name="optionn" value="" placeholder="Product Name">
</div>
<input type="submit" id="add" name="add" value="Save" class="" <!--onclick="myFunction()-->">
When you hit submit, you'll reload the page and lose your data. By using localStorage and JSON.stringify() you are able to save the data locally in your browser and fetch it when you load your page.
Since localStoragecan only store strings, you'll have to convert your object to a string. That's where JSON.stringify() comes into play. And when you fetch it, you can use JSON.parse() to convert it back to an object.
$("#btnSubmit").click(function() {
var data = {};
data.Text = $("#myText").val();
data.isProcessed = false;
localStorage.setItem("myData", JSON.stringify(data));
});
//On load
var data = localStorage.getItem("myData");
var dataObject;
if (data != null) //There's stored data
{
dataObject = JSON.parse(data);
$("#myText").val(dataObject.Text)
localStorage.removeItem("myData"); //Remove data, otherwise it'll be there for a long time.
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<form method="post">
<input type="text" id="myText" />
<button type="submit" id="btnSubmit">Submit</button>
</form>
</div>
More information on localStorage: W3Schools
More information on JSON.stringify and JSON.parse: MDN
I don't know if the snippet will work, since it'll submit a post. Copy this snippet and try it on your local system.
EDIT
As I made a tiny mistake myself, I updated my snippet. But as I suspected, SO doesn't allow access to localStorage.
And ofcourse, you'll have to put this code in your $(document.ready(function() { ... }); for it to work. I did forget to add a <form></form> to my HTML snippet. And I just tested it on my local system and it's working fine.
You can try with localStorage. It's key-value storage that all modern browsers have. There're simple libraries to write to localStorage with fallback to cookies if you need old browser support (written by javascript instead of server side scripts).
I'll give you an example with localStorage:
//emulating that the form was showed (save clicked) and the value true stored on the localStorage
localStorage.setItem('displayedForm', true);
//initializing the state of the page
initialize();
function showHide() {
var div = document.getElementById("hidden_form");
if (div.style.display == 'none') {
div.style.display = '';
localStorage.setItem('displayedForm', true);//if the conditions are meet to display the form, store it on the localStorage
} else {
div.style.display = 'none';
localStorage.setItem('displayedForm', false);//if the conditions are **NOT** meet to display the form, store it on the localStorage as well
}
}
function initialize() {
if (localStorage.getItem('displayedForm') === true || localStorage.getItem('displayedForm') === 'true') {
var div = document.getElementById("hidden_form");
div.style.display = '';
}
}
Working Fiddle: https://jsfiddle.net/y0uep73e/
Facing this problem myself, I wrote a simple library to automatically handle saving and loading form data via local storage: https://github.com/FThompson/FormPersistence.js
Example which saves data upon unload and loads data upon load:
<script src='https://cdn.jsdelivr.net/gh/FThompson/FormPersistence.js#1.0.1/form-persistence.min.js' type='text/javascript'></script>
<script type='text/javascript'>
window.addEventListener('load', () => {
let myForm = document.getElementById('my-form')
FormPersistence.persist(myForm)
})
</script>
Related
I have two different pages. In the first one I have a form with name and email, and the second page should be the result page, and I want to show dynamically the name and email of the user from the form of the first page in the second page, and I precise, I want all this in pure javascript, not php. I tried the localStorage method, and this is what I got so far:
First page: Form page
HTML:
<label>Name:</label>
<input type="text" id="name" />
<label>Email</label>
<input type="text" id="email" />
<button onclick="testVariable()">Submit</button> <br />
Javascript
function testVariable() {
var strText = document.getElementById("name").value;
var strText1 = document.getElementById("email").value;
var result = strText + ' ' + strText1;
if (typeof(Storage) !== "undefined") {
// Store
localStorage.setItem("programX").textContent = result;
}
}
Second page:Result page
HTML:
<p>Hi
<span id="result"></span> thank you for subscribing to our service
</p>
Javascript:
// Check browser support
if (typeof(Storage) !== "undefined") {
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("programX");
} else {
document.getElementById("result").innerHTML = "Browser does not support Web Storage.";
}
localStorage does not have any textContent property.
To set a localStorage
localStorage.setItem('key', 'value');
To get a localStorage value
localStorage.getItem('key');
So, what you are doing to set localStorage is wrong.
Replace
localStorage.setItem("programX").textContent = result;
with
localStorage.setItem("programX", result);
I`m trying to keep the information from a form.
<form name="welcome_form">
<p>Prvi igrac: <input type="text" name="prvi"></p>
<p>Drugi igrac: <input type="text" name="drugi"></p>
</form>
<button onclick="submit_form();">Zapocni igru!</button>
Submit form validates data from input form, and redirects the user to another page.
How can i keep the data from the form on the redirected page
Without using jquery,php, just pure javascript.
I tried using cookies, but it didnt work for me.
var prvi_igrac,drugi_igrac;
function isValid(unos)
{
return /^\w{3,15}$/.test(unos);
}
function submit_form()
{
prvi_igrac = document.forms["welcome_form"]["prvi"].value;
drugi_igrac = document.forms["welcome_form"]["drugi"].value;
//alert(isValid(prvi_igrac));
if(isValid(prvi_igrac) == false || isValid(drugi_igrac) == false)
{
alert("Ime mora sadrzati 3-15 karaktera i samo slova,brojeve i donju crtu!");
return;
}
document.cookie = "prvi_igrac="+prvi_igrac;
var x = document.cookie;
alert(x);
}
Tnx in advance
You can use localstorage to store your form data on first page using following code.
localStorage.setItem('key', 'your data')
and then on redirected page yoou can get with below code
localStorage.getItem('key')
I'm about to code, in Javascript some code (involving looping on each <input> and adding listeners):
allowing, after keypress, to save all <input> values to localStorage
restore all <input> values from localStorage in the case the page/browser has been closed and reopened on the same page
But maybe is there an automatic way, provided by the browsers?
e.g. by adding an attribute to <input>, similar to <input autofocus> (which is not related here)
Question: is there an autosave feature of <form> <input> HTML tags?
As far as I know, there is no built-in way to do that, you should do it manually;
function persist(thisArg) {
localStorage.setItem(thisArg.id, thisArg.value);
}
<input id="test" onchange="persist(this)" />
persist and retrieve all together:
function persist(event) {
localStorage.setItem(event.target.id, event.target.value);
}
// you may use a more specific selector;
document.querySelectorAll("input").forEach((inputEl) => {
inputEl.value = localStorage.getItem(inputEl.id);
inputEl.addEventListener("change", persist);
});
<input id="test" />
there is no automatic way to do that.
you have two options :
save the data by code
example:
localStorage.setItem('testObject', JSON.stringify(yourObject)); // for storing data
JSON.parse(localStorage.getItem('yourObject')); // for retrieving data
code snippet:
// for saving data
function saveData(el) {
localStorage.setItem(el.id, JSON.stringify(el.value));
}
// for retrieving data on page load
function getData() {
var inp = document.getElementById("inp");
inp.value = JSON.parse(localStorage.getItem('inp')) || "";
}
<body onload="getData()">
<input id="inp" onchange="saveData(this)" />
</body>
try a helper library like persisto
Based on the accepted answer, here is a one-liner that can be useful:
document.querySelectorAll('input:not([type="submit"])').forEach(elt => { elt.value = localStorage.getItem(elt.name); elt.addEventListener("change", e => { localStorage.setItem(e.target.name, e.target.value); }); });
It serializes/deserializes the <input>s to localStorage, indexed by their attributes name.
On my site I have a form that posts to an iframe, both parent and iframe window is on my page, domain, etc.
<iframe id="ifc1" style="display:none;" name="ifc"></iframe>
<div id="couponbox">
<form enctype="multipart/form-data" id="promo-form" class="form-inline" action="" method="post" target="ifc">
<div class="form-group">
<input type="text" name="..." placeholder="Enter Here" id="..." class="form-control" value="">
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Apply Now" placeholder="">
</div>
</form>
</div>
The form is posting successfully, and on the iframe page there is a div that shows the alert/results.
<div id="alert" class="alert alert-success">.....</div>
I am trying to use JS or Jquery to find which text is showing in the alert (ie. fail, success, etc.), and then echo a message on the parent page.
// Attempt at a supposed solution
// reference to iframe with id 'ifrm'
var ifrm = document.getElementById('ifc1');
var base = document.getElementById('couponbox');
// using reference to iframe (ifrm) obtained above
var win = ifrm.contentWindow; // reference to iframe's window
// reference to document in iframe
var doc = ifrm.contentDocument? ifrm.contentDocument: ifrm.contentWindow.document;
// reference to form named 'demoForm' in iframe
var form = doc.getElementById('alert');
if (form === "Credits successfully deposited into your account") {
// Tried jQuery
$('#couponbox').append('success')
}
// jQuery attempt
if($("#ifc1").contents().text().search("successfully deposited")!=-1){
alert("found");
}
So far I haven't been able to get anything to work. Any help is appreciated.
UPDATE --
I am currently trying to use this code --
$('#ifc1').on('load', function() {
if($.trim($("#ifc1").contents().find("#alert").html()) === "Credits successfully deposited into your account"){
$("#couponbox").prepend("<b>Successfully Deposited</b>");
$("#buy").replaceWith( '<input type="submit" value="Publish" name="upsub" id="upsub" class="pubbtn action-button" placeholder="">'
} else {
$("#ifc1").contents().find("#alert").appendTo("#couponbox");
}
});
I've placed it at the end of my page. It's giving me errors with my other scripts though.
Commenting out the replacewith function, doesn't give the looping error ---
$('#ifc1').on('load', function() {
if($.trim($("#ifc1").contents().find("#alert").html()) === "Credits successfully deposited into your account"){
$("#couponbox").prepend("<b>Successfully Deposited</b>");
//$("#buy").replaceWith( '<input type="submit" value="Publish" name="upsub" id="upsub" class="pubbtn action-button" placeholder="">'
} else {
$("#couponbox").prepend("<b>Incorrect</b>");
}
});
To get the text of #alert div from iframe you can use
$(document).ready(function(){
$("#ifc1").contents().find("form#promo-form").on("submit",function(){
alert($("#ifc1").contents().find("#alert").html());
});
});
It will give you the text in #alert div.
Update
$('#ifc1').on('load', function() {
alert($("#ifc1").contents().find("#alert").html());
});
When you submit a form in iframe it also triggers load event of iframe. Check if you can get a value on load function?
Update 2
$('#ifc1').on('load', function() {
if($.trim($("#ifc1").contents().find("#alert").html()) === "success"){
alert("finish");
}
});
you can use $.trim to remove all white spaces around the string and the check if it matches with "success". TRIM
You're trying to get the contents of the form element, but you're not using innerHTML.
var ifrm = document.getElementById('ifc1');
var base = document.getElementById('couponbox');
var win = ifrm.contentWindow; // reference to iframe's window
var doc = ifrm.contentDocument? ifrm.contentDocument: ifrm.contentWindow.document;
var form = doc.getElementById('alert');
if (form.innerHTML.includes("Credits successfully deposited into your account")) {
$('#couponbox').append('success')
}
Today I came up with something interesting at one of my projects. I have a search box with several fields(ex.: licence plate, date of buy, state) and some of them has an operator field. (ex.: >, <, =)
After I post my search and returns the result say it i want to change one of my operators but always changes to the first element of it. Is there anything that i can do to "save" the state of the fields?
I could do it with sessions but it is a fairly big form so it would be ugly.
Thank you for your answers!
A small snippet for you using localStorage:
I have timed as 5 seconds to take a backup of everything on the form.
Loads the stuff from the localStorage once the page is loaded.
window.onload = function () {
if (typeof(Storage) !== "undefined") {
if (typeof localStorage["name"] !== "undefined") {
document.getElementById("name").value = localStorage["name"] ? localStorage["name"] : "";
document.getElementById("pass").value = localStorage["pass"] ? localStorage["pass"] : "";
}
// Code for localStorage/sessionStorage.
setInterval(function () {
document.getElementById("saving").innerHTML = 'Saving...';
setTimeout(function () {
document.getElementById("saving").innerHTML = '';
}, 500);
localStorage.setItem("name", document.getElementById("name").value);
localStorage.setItem("pass", document.getElementById("pass").value);
}, 5000);
}
};
strong {display: inline-block; width: 50px;}
<form action="">
<strong>Name:</strong> <input type="text" name="name" id="name" /><br>
<strong>Pass:</strong> <input type="password" name="password" id="pass" /><br>
<span id="saving"></span>
</form>
Note: localStorage is a sandboxed feature in snippets. So doesn't work here. Check in JSBin: http://output.jsbin.com/bubukunoke
I solved the problem with sessions at the end.
When I post the form I save all of the content into a session and in the View I check if it exists and if yes I set it to as the field value.