In the script below, I try to record in the bowser the name of the users who connect to my application. If it is the first time that a user connects, when he presses the "submit" button to connect to the application I want a message "Welcome" + name + "! If the user has already connected (his name is already registered in the localStorage), when he presses the submit button, I want a "Welcome back" + name + "!
Thank you for the comments below, I tried to take them into account. When I run the updated code below, only welcome appear on the message. The name of the user is not included on the message. How can I modify my code to correct this problem?
Thank you in advance for your advice.
JS script:
let myButton = document.getElementById ("myButton");
let myText = document.getElementById ("username");
function store() {
let n = 0;
while (localStorage.getItem("username" + n)) {
n++;
}
localStorage.setItem("username" + n, myText.value);
}
function welcomeUsername(){
let resultMessage = "Welcome "
let n = 0;
while (n) {
let user = localStorage.getItem("username" + n);
if(myText.value != user){
resultMessage += myText.value + "!";
break;
} else {
resultMessage += "back" + myText.value + "!";n++;
}
}
alert(resultMessage);
}
HTML Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login Page</title>
</head>
<body>
<br />
<br />
<div class ="login_card"></div>
<div class = "log_head">
<h1>Login</h1>
</div>
<div class = "log_body">
<br />
<label for="uname"><b>Please enter your username below and click on submit:</b></label> <br>
<input type="text" value = "Enter username" onfocus = 'this.value =""' id = "username"> <br>
<br> <br>
<input type="button" onClick="welcomeUsername();location.href ='/index';" value = "Submit" id = "myButton">
</div>
</div>
this part of your code has problem let value = localStorage.getItem("username")
. you cant get any value from your localstorage since you set them 'username'+n
, that;s why your if
statement always run.
can you try this: while (n) {let user = localStorage.getItem("username" + n); if (myText.value == user) {resultMessage += myText.value; break; } else {resultMessage += "back" + myText.value + "!"; n++; }}