Benjamin Sloutsky
Benjamin Sloutsky

Reputation: 63

Why doesn't this local storage code work?

This is my code for index.html

<form action = "indo.html">
      <input type = "text" id = "tex">
      <button id = "tex">Submit</button>

    </form>
    <script>

      var o = document.getElementById("tex").value;
      localStorage.setItem("three", o);
    </script>

This is my code for indo.html

<script>
  var n = localStorage.getItem("three");
  document.write("Welcome "+n);
</script>

Upvotes: 1

Views: 54

Answers (2)

H.T
H.T

Reputation: 130

If you want save data into local-storage i suggest below code:

<form >
  <input type = "text" id = "tex">
  <button id = "texb">Submit</button>
</form>

function fun_sub(){
 const val = document.getElementById("tex").value;
  localStorage.setItem("three", val);
  console.log(localStorage.getItem("three"));
  window.open("/indo.html", "_self");
}

In your code, name id of input element and button element is same! this mistake return error if you call getElementById in javascript ,and you must consider that when you write a code and you want call code again after render page, you should call it in a function.

Upvotes: 0

prasanth
prasanth

Reputation: 22500

Actually its working .But the value is empty .set Initial value on input .Because its set value on page load not after the form submit

Try this

<form action="indo.html">
  <input type="text" id="tex" value="something">
  <button id="tex">Submit</button>

</form>
<script>
  var o = document.getElementById("tex").value;
  localStorage.setItem("three", o);
</script>

indo.html

<script>
  var n = localStorage.getItem("three");
  document.write("Welcome " + n);
</script>

Upvotes: 3

Related Questions