Skip to content
Advertisement

How do I store the content of a variable for later use in other function (Javascript)

I have been trying to make a simple Register/Login system in JS. I tried to get the username/password values through user inputs and turn them into variables using a register() function. After that, however, these variables no longer hold any value, and I need them to compare with the new login username/password to check if they match in order to login.

Here’s what I tried.

The function below attributes the user’s input to the respective variables successfully. The ID’s are from a text input in a HTML file.

JavaScript

When I click the ‘register’ button in the html page, the function is called (onclick=”register()”), and I am redirected to the login page.

Here’s the code for the login session:

JavaScript

It doesn’t work because in the code above, user1 and pass1 are “not defined”, according to the console. How do I keep the values of these variables stored after getting them in the first function(register) in order to use it when the second function(login) is used?

Advertisement

Answer

Please refer the below code,

JavaScript
  • Store all users in array after successful registration
  • While login, loop through the registered users array to check whether the user has already registered or not and decide how to handle the logic.
  • As PM 77-1 mentioned in the comment, please be aware that getElementById(ID) returns us the element itself (the tag itself), if we want to access it text content we can use either getElementById(ID).textContent or getElementById(ID).innerText
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement