Reputation: 23
I have set up local storage to pass two form inputs from a form on page A to a form on page B. This works fine... but if I navigate to page B without inputting anything in page A, or navigate directly to page B, the form inputs are blank. How do I get local storage to pass variables only if there is a variable to pass?
Thanks for any help!
Here's the code I have so far: Page A.
function pageSel() {
var parseAmount = document.getElementById("stepperAmount").value;
var parseMonth = document.getElementById("stepperMonth").value;
localStorage.setItem("amountKey", parseAmount);
localStorage.setItem("monthKey", parseMonth);
}
Page B.
function pageSel2() {
var parseAmount2 = localStorage.getItem("amountKey");
var parseMonth2 = localStorage.getItem("monthKey");
document.getElementById("demo1").value = parseAmount2;
document.getElementById("demo2").value = parseMonth2;
}
function roundAmount() {
var x=document.getElementById("demo1");
x.value=Math.round(x.value/250)*250;
}
function roundMonth() {
var x=document.getElementById("demo2");
x.value=Math.round(x.value/12)*12;
}
pageSel2();
Upvotes: 0
Views: 847
Reputation: 23
If anyone else is struggling with this, I've come up with a solution:
The Page A code is fine as it is. Page B is now:
function pageSel2() {
var parseAmount2 = localStorage.getItem("amountKey");
var parseMonth2 = localStorage.getItem("monthKey");
document.getElementById("demo1").value = parseAmount2 ? parseAmount: 1000;
document.getElementById("demo2").value = parseMonth2 ? parseAmount: 36;
}
function roundAmount() {
var x=document.getElementById("demo1");
x.value=Math.round(x.value/250)*250;
}
function roundMonth() {
var x=document.getElementById("demo2");
x.value=Math.round(x.value/12)*12;
}
pageSel2();
Upvotes: 0
Reputation: 23
Unfortunately this doesn't have any effect. I think I should add that when navigating directly to page B, the default values are displayed for a second and then they appear to be overwritten with blank data.
Upvotes: 0
Reputation: 172
Just check if a value is present before setting localStorage:
function pageSel() {
var parseAmount = document.getElementById("stepperAmount").value;
var parseMonth = document.getElementById("stepperMonth").value;
if (parseAmount) {
localStorage.setItem("amountKey", parseAmount);
}
if (parseMonth) {
localStorage.setItem("monthKey", parseMonth);
}
}
Upvotes: 1