Reputation: 309
I used javascript to save username information in local storage, so that when the user logs in, the username appears in the profile page. My problem is that I don't know how to get the username from the local storage and write it in my html page. So far I have this:
function user(){
document.write(localStorage.getItem("name1");
}
This code is not working and I don't know how to make it work.
Upvotes: 0
Views: 6883
Reputation: 28437
You need to assign the value to an existing HTML element, e.g.
document.getElementById("test").innerHTML = localStorage.getItem("name1");
HTML should in such a case contain an element with ID test:
<div id="test"></div>
You might first want to check if the key actually exist though, like so:
if (localStorage.getItem("name1") != null) {
document.getElementById("test").innerHTML = localStorage.getItem("name1");
}
Upvotes: 2
Reputation: 275
if (typeof (localStorage.getItem("name1")) != null && (localStorage.length != 0)) {
var name1= localStorage.getItem("name1");
}
else {
alert("local storage kills");
}
The above code will be useful for you..
Upvotes: 0
Reputation: 6656
Try this maybe could help.
function getUser(){
name = localStorage.getItem("name");
if (name == null || name == "null"){
alert("Howdy, Stranger!");
name = prompt("Who are you?");
localStorage.setItem("name", name);
} else {
alert ("Hi, " + name + "!");
} // end getUser
} // end function
Upvotes: 0