skip to Main Content
//gets the username from the text box
function getUsername() {
let username = document.getElementById("usernameBox").value;
}
//alerts the user there username p.s. the site is still under development.
function sayUsername() {
alert(userename);
}

I keep getting the error message that the username variable does not exist, even though it is set in the function above. So my question is, how do I make the username variable set in both functions?

I have tried to put all the code above plus the other code for website in the same function, but that gives me errors. Then I have tried to make the username and password get put into an array but the values change when a different person logs in. So how do I make the variables work in all functions?

2

Answers


  1. let username
    
    function getUsername() {
      username = document.getElementById("usernameBox").value;
    }
    
    function sayUsername() {
      alert(userename);
    }
    
    Login or Signup to reply.
  2. You can make it global by declaring it outside the function but global variables give rise to errors, so better will be call the sayUsername from getUsername function and pass username as a paramater to the function

    function getUsername() {
      let username = document.getElementById("usernameBox").value;
      sayUsername(username)
    }
    
    function sayUsername(userename) {
      alert(userename);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search