0

var Words = ['little', 'lump', 'house', 'begs', 'software']; // Word Array

var word = Words[Math.floor(Math.random() * Words.length)]; // calls random word
console.log(word); 
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link href="Css.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="Javascript.js"></script>
</head>

<body>
 <body>
             
              <h1 class="gamefunc">Add words here!</h1>
              <form class="title" id="frm1">
              <br>
                Word: <input type="text" name="newWord" id="words">
      <br>
      <br>
      <button type="button" class="btn4" onclick="myFunction()">Submit Word</button>
      <br>
     
      <a href="Home.html"><button class="btn4" id="addWord" type="button">Home</button></a>
              </form>
              <br>
<script>
function myFunction(){
              var x = document.getElementById("words").value;
              console.log(x);
              Words.push(x);
    
 
              console.log(Words)
}
</script>


</body>
</html>

i have pushed words to an array in my code but what i want to achieve is the ability to locally or sessionly store the pushed word in the array, so that when i change between my html pages the new added word will be in the array

1 Answers1

0

One option would be to use sessionStorage, as demonstrated below:

function myFunction() {
  var x = document.getElementById("words").value;
  console.log(x);
  Words.push(x);

  sessionStorage.setItem('Words', Words);

  console.log(Words)
}

var Words = sessionStorage.getItem('Words');

if (Words == null) {
  Words = ['little', 'lump', 'house', 'begs', 'software']; 
} else {
  Words = Words.split(',');
}
<h1 class="gamefunc">Add words here!</h1>
<form class="title" id="frm1">
  <br> Word: <input type="text" name="newWord" id="words">
  <br>
  <br>
  <button type="button" class="btn4" onclick="myFunction()">Submit Word</button>
  <br>

  <a href="Home.html"><button class="btn4" id="addWord" type="button">Home</button></a>
</form>

Please note that you will be unable to run this snippet on Stack Overflow due to the sandbox mode, but if you run this locally in your browser, you will see that it will function as you would expect.

Adam Chubbuck
  • 1,612
  • 10
  • 27