Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

319
Visualizações
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 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

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 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda