I’m making a dynamic website that need to show the user’s name in the heading. The heading should say ‘Hello, ‘, when the user enters their name into the text box and presses the button. And the name has to stay on the page even if I refresh the page.
What will be the javascript functions and html codes to implement this?
However, to implement this, the site need to read the query string when the page is loaded, not when the button is pressed. How can I write functions for the onload
event for this?
I’ve tried this, but this doesn’t work.
function setUserName() { var userName = document.getElementById("userName").value; localStorage.setItem("userName", userName); } function getUserName() { var userName = localStorage.getItem("userName"); return userName; } function displayUserName() { var userName = getUserName(); if (userName) { document.write("Hello, " + userName); } else { document.write("Hello, world!"); } }
<input type="text" id="userName"> <button onclick="setUserName()">Set Name</button> <body onload="displayUserName()"></body>
Advertisement
Answer
Try this code, It might helpfull to you
function setUserName() { var userName = document.getElementById("userName").value; localStorage.setItem("userName", userName); location.reload(); } function getUserName() { var userName = localStorage.getItem("userName"); return userName; } function displayUserName() { var userName = getUserName(); if (userName) { document.getElementById("helloText").textContent = "Hello, " + userName; } else { document.getElementById("helloText").textContent = "Hello, world"; } }
<span id="helloText"></span> <input type="text" id="userName" name="userName"> <button onclick="setUserName()">Set Name</button> <body onload="displayUserName()"> </body>
Local storage wont work with the snippet by the way