I am trying to set the element #welcome_banner
by using a function in javascript that takes a form submission and sets it to localStorage
and then pulls that info and sets it onto an <h1>
tag. Apparently it works but only changes the tag for a millisecond and then it disappears! I have tried doing the .innerHTML
setting in various places inside and outside of the function clickHandler()
and in the main body of the script. I am certain this is something superbasic I am missing.
<!DOCTYPE html>
<html>
<head>
</head>
<script >
//set display name to form submission, set welcome banner to display name
function clickHandler () {
document.querySelector('#display_name').onsubmit = function() {
localStorage.setItem('dn', dn);
document.querySelector('#welcome_banner').innerHTML=changeWelcomeBanner;
}
};
function changeWelcomeBanner () {
var dn = localStorage.getItem('#dn').value;
var welcomeBanner = document.getElementById('#welcome_banner');
welcomBanner.innerHTML = `Hello ${dn}`;
}
</script>
<title>Project 2</title>
<body style="background-color:#ff3300;">
<h1 id="welcome_banner"></h1>
<form id="display_name">
<input id="dn" autocomplete="off" autofocus placeholder="" type="text">
<button>set display name</button>
</body>
</html>
The steps to do this are as follows:
localStorage.setItem('dn', dn);
document.addEventListener("DOMContentLoaded", function(event) { // code to check local storage goes here... });
var dn = localStorage.getItem('dn').value;
and if there is a value there, set the innerHtml of the <h1>
to that value, like you're doing here: welcomBanner.innerHTML = 'Hello ${dn}';
I think you might have had a stray # character in your localStorage.getItem call that I removed in the steps above. You might also want to have default text you post if there's nothing found in localStorage when you check.
Here's a simplified example: If you are calling a function to get the value from Local Storage, be sure you have a return
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <h1 id="welcome"></h1> <input type="text" id="something"> <button type="button" id="click">CLICK ME</button> <script> document.getElementById("click").addEventListener("click", function(){ var x=document.getElementById("something").value; document.getElementById("welcome").innerHTML=x; localStorage.setItem('x', JSON.stringify(x)); document.getElementById("welcome").innerHTML = getData(); }); function getData(){ var retrieve=localStorage.getItem('x'); return JSON.parse(retrieve); //Now return the value } </script> </body> </html>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.