2

I am new to javascript and DOM manipulation. So I have this form I have created basically to get names of players. What I want to achieve is to get the player names and display them on the games page once they are redirected after clicking on the button. It does not display the line of code and returns an error:

(VM4444:1 Uncaught ReferenceError: player1 is not defined at :1:1).

function next() {
  var player1 = document.getElementById('play1').value;
  var player2 = document.getElementById('play2').value;
  if (player1 === '' || player2 === '') {
    document.getElementById("error").style.color = "red";
    document.getElementById("error").innerHTML = "Please enter both names";
  } else {
    location.href = "game.html";
  }
  document.getElementById('name1').innerHTML = player1.value;
  document.getElementById('name2').innerHTML = player2.value;
  console.log(player1, player2);
}
<div class="col-lg-4 col-md-4 col-sm-12 form">
  <form>
    <small class="form-text text-muted">We'll never share your details with anyone else.</small>
    <div class="form-group">
      <label for="player1">Player 1</label>
      <input type="text" class="form-control" id="play1" aria-describedby="play1help">

    </div>
    <div class="form-group">
      <label for="player1">Player 2</label>
      <input type="text" class="form-control" id="play2" aria-describedby="play1help">
    </div>
  </form>
  <button class="btn btn-lg btn-primary btn-block mt-3" onclick="next();">Start</button>
  <a href="C:\Users\Slim\Documents\webdevelopment\dicee\game.html" alt=""></a>
</div>
eboakyegyau
  • 225
  • 1
  • 13
Seyi Agboola
  • 59
  • 1
  • 5
  • Does this answer you question - https://stackoverflow.com/questions/17502071/transfer-data-from-one-html-file-to-another? There are multiple methods, you can either send the data to be displayed on page in the `URL`(if data is not sensitive) and retrieve the data from URL and display it or using localstorage. – random Apr 03 '20 at 03:32

1 Answers1

0

Using localStorage you can easily achieve this,

localStorage["key"] = value;

In next page you can get the value by using

value = localStorage["key"];

First Page

function next() {
  var player1 = document.getElementById('play1').value;
  var player2 = document.getElementById('play2').value;
  if (player1 === '' || player2 === '') {
    document.getElementById("error").style.color = "red";
    document.getElementById("error").innerHTML = "Please enter both names";
  } else {
    location.href = "game.html";
  }
  document.getElementById('name1').innerHTML = player1.value;
  document.getElementById('name2').innerHTML = player2.value;
  localStorage["player1"] = player1;
  localStorage["player2"] = player2;
  console.log(player1, player2);
}

Next Page

function getPlayer() {
      player1 = localStorage["player1"];
      player2 = localStorage["player2"];
      console.log(player1,player2)
    }
Harshith J Poojary
  • 316
  • 10
  • 26