Home > Mobile >  How to access an object from another file in JavaScript?
How to access an object from another file in JavaScript?

Time:12-10

I want the score of the game played stored in the usrObj next to topScore in the local storage. However, it only stores the score next to the user's name.

js code from index.html

<script>
            loadRankingTable();
            window.onload = ()=> {
            //Check login
            if(sessionStorage.loggedInUser !== undefined){
                window.localStorage.setItem(sessionStorage.loggedInUser, highscore);
                document.getElementById("Greeting").innerHTML = sessionStorage.loggedInUser;
            }
        } 

        </script>

prac.js

function register(){
    let password1 = document.getElementById("PasswordInput").value
    let password2 = document.getElementById("PasswordInputConfirm").value
    let username = document.getElementById("Username").value
    let name = document.getElementById("NameInput").value;
    let password = document.getElementById("PasswordInput").value;                        
    let usrObj = {
        username: username,
        password: password,
        topScore: 0     
    }
    
    if (password1 == password2){
        localStorage[name] = JSON.stringify(usrObj);
        document.getElementById("FeedbackPara").innerHTML= "";
    }   
    else{
        document.getElementById("FeedbackPara").innerHTML= "Passwords don't match.";
    }
}

so basically instead of the local storage storing data like this: "user, 200", i want it to be like this: "username: username, password: password, topScore: 200 "

CodePudding user response:

Retrieve the current value of the local storage as JSON, update the score, and then save it again.

loadRankingTable();
window.onload = () => {
  //Check login
  if (sessionStorage.loggedInUser !== undefined) {
    let oldData = localStorage.getItem(sessionStorage.loggedInUser);
    if (oldData) {
      oldData = JSON.parse(oldData);
      oldData.topScore = highscore;
      localStorage.setItem(sessionStorage.loggedInUser, JSON.stringify(oldData);
    }
    document.getElementById("Greeting").innerHTML = sessionStorage.loggedInUser;
  }
}

  • Related