0

I want to be able to save an input that I enter on a site, when the page is refreshed

function num() {
  var number = prompt("Enter number");
  document.getElementById("number").innerHTML = number;

}
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td,
th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}
<button onclick="num()">Click here to edit number</button>

<table>
  <tr>
    <th colspan=2>Something</th>
  </tr>
  <tr>
    <td>Name</td>
    <td id="number"><!-- this is where I want input to show --> </td>
  </tr>
</table>

I want to be able to refresh the page, and have the number that I input, stay there.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
marsnebulasoup
  • 2,530
  • 2
  • 16
  • 37
  • 2
    Use localStorage, or sessionStorage, depending upon your requirements, then. – connexo Mar 01 '18 at 19:36
  • 2
    State is not maintained across page refresh. You need to store data either on a server, or in the browser's localStorage, and then retrieve it for display on the next page load. – Daniel Beck Mar 01 '18 at 19:37
  • You could use a cookie as a very basic solution, [link on cookies](https://www.w3schools.com/js/js_cookies.asp). or i found this link for your [answer](https://stackoverflow.com/questions/38930144/keep-input-value-after-refresh-page) – JakeTheSnake Mar 01 '18 at 19:38

1 Answers1

0

try updating your code with the following

//if value exist place it otherwise show 0
function onloadFunc() {
  document.getElementById("number").innerHTML = localStorage.getItem("number") || 0;
}

window.onload = onloadFunc;

function num() {
  var number = prompt("Enter number");
  // set the value in local storage
  localStorage.setItem("number", number);
  document.getElementById("number").innerHTML = number;
}
Ash
  • 564
  • 2
  • 5
  • 23