简体   繁体   中英

Retrieving AND Displaying saved data from local storage inanother web page

I am doing a school project on creating a web site. I have managed to save user data into local storage upon signing up for an account. I want to retrieve and display the saved user data from local storage into an edit profile page, such that when I load the edit profile page, there would be some data already shown in the page. For example in social media accounts whenever we want to edit our profile, our current information would be shown, and we just edit our info from that page. How do I achieve this?

Here are my codes:

<script>
    var currentUser=null;
    document.addEventListener("DOMContentLoaded",loadUserData);

    function loadUserData() {
        currentUser = localStorage.getItem("currentUser");
        if(currentUser!=null) {
            currentUser = JSON.parse(currentUser);

            console.log(currentUser.username);
            console.log(currentUser.name);
            console.log(currentUser.password);
            console.log(currentUser.email);
        }
    }
</script>

I know the console.log only shows the data in console, but I need the data to be shown in the text box instead when users go to the edit profile page. Is the following script correct to display a username in the username text box?It didn't work for me though.

<p>
    <label for="newusername">Change Username:</label>
    <input type="text" name="username" onload="valueAsPlaceHolder();"
    id="username" required="required"/>

    <!--<script>
    function valueAsPlaceHolder() {
        var changeUsernameInput = document.getElementById("username");
        localStorage["username"] = changeUsernameInput.value;

        var changeUsernameSetting = localStorage["username"];
        if (changeUsernameSetting == null) {
            changeUsernameInput.value = "";
        }
        else {
            changeUsernameInput.value = changeUsernameSetting;
            }
        }
    </script-->
</p>

You should have to modify the loadUserData function like below. I have set example for username you can follow for all fields like name, email and password.

function loadUserData() {
    currentUser = localStorage.getItem("currentUser");
    if(currentUser!=null) {
        currentUser = JSON.parse(currentUser);

        document.getElementById('username').value = currentUser.username;
    }
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM