Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

143
Vistas
javascript - localStorage - issue with a loop and message to display

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> 
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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++; }}

about 4 years ago · Juan Pablo Isaza Denunciar

0

Try this.

const btn = document.getElementById('myButton');

// get a welcome message
const welcomeText = (name) => {
  // store the name as an array type, initialize if it does not exist
  let names = localStorage.getItem('usernames');
  names = names == null ? [] : names;
  // check if the name exists and decide the welcome message according to the result
  if (names.includes(name)) {
    return `Welcome back ${name}`;
  } else {
    // update storage information
    names.push(name);
    localStorage.setItem('usernames', names);
    return `Welcome ${name}`;
  }
};

// send name and call method
const submit = () => {
  const name = document.getElementById('username').value;
  alert(welcomeText(name));
};

btn.addEventListener('click', submit);
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda