I created a form to collect user information and then saved it in localstorage.
To finish the programming I want to display this information in an HTML page. However, the way I did the information appears and disappears quickly.
<!DOCTYPE html>
<html>
<body>
<p>Saved info is:</p>
<p id="currentDate"></p>
<p id="currentReprodutor"></p>
<p id="currentMatriz"></p>
<script>
store();
function store(){
const inputDate = document.getElementById('datepicker').value;
const inputRep = document.getElementById('rep').value;
const inputMatriz = document.getElementById('matriz').value;
window.localStorage.setItem('Date', String(inputDate));
window.localStorage.setItem("Rep", String(inputRep));
window.localStorage.setItem("Matriz", String(inputMatriz));
document.getElementById("currentDate").innerHTML = window.localStorage.getItem("Date");
document.getElementById("currentRep").innerHTML = localStorage.getItem("Rep");
document.getElementById("currentMatriz").innerHTML = localStorage.getItem("Matriz");
}
</script>
</body>
</html>
Is there any way to display the user values in html page from local storage?
CodePudding user response:
You are setting the key "Rep" but then getting "Reprodutor". This might be the issue why you don't see the values appear on the page
CodePudding user response:
Your code does the following steps (in order):
- Read value of DOM elements
- Save that value to LocalStorage
- Read value from LocalStorage and inject into DOM elements
Since the DOM elements are empty on page load, you'll push 'nothing' to the LocalStorage, read 'nothing' so there's nothing to show.
Consider the following example where we change the order if needed:
store();
function store(){
// Get elements
const inputDate = document.getElementById('datepicker');
const inputRep = document.getElementById('rep');
const inputMatriz = document.getElementById('matriz');
// IF there is NOTHING in LocalStorage
if (window.localStorage.getItem('Date') === NULL) {
// Set dumy value so we'll not push 'empty' things to LocalStorage
inputDate.innerHTML = 'foo';
inputRep.innerHTML = 'foo';
inputMatriz.innerHTML = 'foo';
// Save to localStorage
window.localStorage.setItem('Date', inputDate.innerHTML);
window.localStorage.setItem("Rep", inputRep.innerHTML);
window.localStorage.setItem("Matriz", inputMatriz.innerHTML);
} else {
// Set to DOM eleemnts
inputDate.innerHTML = window.localStorage.getItem("Date");
inputRep.innerHTML = localStorage.getItem("Rep");
inputMatriz.innerHTML = localStorage.getItem("Matriz");
}
}
<p>Saved info is:</p>
<p id="currentDate"></p>
<p id="currentReprodutor"></p>
<p id="currentMatriz"></p>