Skip to content
Advertisement

Save form values to localStorage

I have been studying JS for a while so at some point a couldn’t complete the assignment that my teacher gave me so its all about to create a input to fill with 3 selectors to change some properties of the text.

What I’m trying to do is:
whenever the user he closes the page and opens it again – apply the values from localStorage back into the form, and apply the styles to an element. I.e:

Font: Roboto
Color: Green
fontSize: 24px

How I am supposed to do it, and why my code is wrong?
Here’s the code :

JavaScript
JavaScript
JavaScript

Advertisement

Answer

  • There’s no need to query the DOM inside a for loop for the same element again and again.
    Cache the elements you plan to reuse beforehand.
  • Use const when the variable value will not change through the life of your app
  • What means “paragragh” you mean paragraph? (BTW, it’s a DIV)
  • There’s no need to use id if you already use name
  • Don’t name a function iterator if its job is clearly to populate a Select box with <option>s. createFontSizeOptions seems like a better choice.
  • Don’t name a function finalItreator it means nothing.
    Describe your function names as concisely, meaningfully, and short as possible.
  • (Actually, you don’t need those functions at all)
  • Don’t name your ID’s PascalCase. Use camelCase.
  • Assign the "input" Event to a class selector, i.e: .command which is assigned to your Select (or other imput) elements.
  • Use a proper name which value is exactly the expected CSS property as camelCase, i.e: fontFamily or fontSize
  • Store into LocalStorage a Stringified Object literal using JSON.stringify
  • Retrieve from localStorage using JSON.parse
  • Create three functions, one that gets the String as Object from localStorage, the second to save an Object to localStorage, and a third one to apply the key/value pairs styles to a desired element using Object.assign
  • Create some reusable DOM utilities to help you with getting or creating elements in the DOM

(Since Stack Overflow Snippets for security reasons doesn’t accept access to localStorage from Iframe, here’s a live jsFiddle demo)

Code:

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement