3

I'm trying to safe a value in localstorage to use it later on other pages, but I can't quite get it to work.

My input field:

<input type="text" name="test" value="" id="test" required />
         <span class="highlight"></span>
         <span class="bar"></span>
         <label>enter something</label>

My script:

<script>

function getStorage(type) {
  var storage = window[type + 'Storage'],
    delta = 0,
    p = document.createElement('p');

  if (!window[type + 'Storage']) return;

  if (storage.getItem('value')) {    
    p.innerHTML = type + 'Storage: ' + storage.getItem('value');
  } else {
    p.innerHTML = type + 'nothing safed';
  }

  document.querySelector('#output').appendChild(p);
}

getStorage('test');


addEvent(document.querySelector('#test'), 'keyup', function () {
  localStorage.setItem('value', this.value);
});


</script>

My output:

    <p id="output"></p>

Note: I'm using h5utils.js (https://java.net/projects/prototype/sources/svn/content/trunk/demosprojects/AjaxAdmin/web/h5utils.js?rev=11) to make it all work, but I can't get output. No errors in the console.

5
  • 2
    Well, there's no such thing as window.testStorage, so your getStorage('test') call will return immediately. Commented Jun 21, 2016 at 17:15
  • 1
    All I see here is a value being written to localStorage with the key "value", then you try to get values out from testStorage, which is meaningless. Call getStorage('local') instead. Commented Jun 21, 2016 at 17:15
  • Thanks for the responses! Will changing getStorage('test') to getStorage('local') do the trick? Commented Jun 21, 2016 at 17:17
  • 1
    Yes. See my answer :) PS Changed "safed" to "saved". Commented Jun 21, 2016 at 17:18
  • 1
    haha, thanks a lot mate! Commented Jun 21, 2016 at 17:21

1 Answer 1

1

You're calling the getStorage function passing a type of 'test', which then attempts to look up window.testStorage which doesn't exist of course.

Use...

getStorage('local');

... instead to look up localStorage.

Sign up to request clarification or add additional context in comments.

1 Comment

stupid mistake, I should take a break and get some coffee. Anyway, thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.