• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

164
Vistas
Saving a text input to separate js files

I'm trying to make a quiz web app with javascript and I am stuck. There are 2 HTML files, one as starter.html and one as index.html. I have an input in my starter file which takes in a username which I want to display later on the index site like:

alert(`Congrats ${playerName} you got all the questions right!`)

and a "submit" link which takes you to the next site and stores a variable like this:

<input type="text" id="username" placeholder="Enter your name"/>
<a id="startGame" href="index.html">Start Game</a>

const inputArea = document.querySelector("#username");
const startButton = document.querySelector("#startGame");

var saveUsername = function () {
  var playerName = inputArea.value;
};

How can i access the playerName variable from the index.html? Firstly, I intended to use a global js file but I miss some declared elements since i have two separate html file and it does not find the elements during the DOM manipulation (cannot read properties of null). I tried using two separate js file but I couldn't find the solution to access data from a javascript file and store it in the second one.

Any ideas?

about 3 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can use localStorage for that purpose. When a user enters his / her name in the textbox you can save the value to localStorgae and fetch the value on the index page.

const usernameInputField = document.querySelector('#username'),
  button = document.querySelector('button');

button.addEventListener('click', () => {
  if (usernameInputField.value != "") {
    localStorage.setItem('user', usernameInputField.value);
  }
  alert('Username Saved Successfully. Starting the game...');
})
<input type="text" id="username" placeholder="Enter your name" />
<button>Start Game</button>

and to get the value back, simply use

if(localStorage.getItem != null && localStorage.getItem('user') != "") {
   console.log(localStorage.getItem('user'));
   // here you can set the name as innerText of some element
}

You can check this out here https://jsfiddle.net/za01kp46/

about 3 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 Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda