0
var itemName; var itemSize; var itemType; var itemColor; window.onload = function() { document.getElementById('item_save').onclick = function() { var item_name = document.getElementById('item_name').value; var item_size = document.getElementById('item_size').value; var item_type = document.getElementById('item_type').value; var item_color = document.getElementById('item_color').value; console.log(item_name + "\t" + item_size + "\t" + item_type + "\t" + item_color + "\tsaving..."); localStorage.setItem(itemName, item_name); localStorage.setItem(itemSize, item_size); localStorage.setItem(itemType, item_type); localStorage.setItem(itemColor, item_color); } var getItemName = localStorage.getItem(itemName); var getItemSize = localStorage.getItem(itemSize); var getItemType = localStorage.getItem(itemType); var getItemColor = localStorage.getItem(itemColor); console.log(getItemName + "\t" + getItemSize + "\t" + getItemType + "\t" + getItemColor + "\tsaved...") } 

Say if I enter 1 for the item_name input, 2 for the item_size input, 3 for the item_type input and 4 for the item_color input, it keeps displaying in console as:

"4 4 4 4 saved...

1 2 3 4 saving..."

I was wondering why it displays the saved console.log first as well and making all the numbers 4 in the saved console.log, need advice.

4
  • 4
    The first argument to .setItem() should be a string. You're passing uninitialized variables, so that'll be taken as the item name "undefined". Commented Apr 10, 2020 at 14:19
  • how should i change it? Commented Apr 10, 2020 at 14:28
  • 1
    The variables like itemName etc are not really necessary, but you could initialize them with string values (var itemName = "itemName"; etc). Or you could use the strings directly. Commented Apr 10, 2020 at 14:31
  • Thanks :) How do I make it so the saved console.log displays after? (Never mind, im dumb lol) Commented Apr 10, 2020 at 14:40

1 Answer 1

2

The "saving" console appears on event "click".

The "saved" console appears on event "load".

Of course, the loading is done before any other event is fired, liked "click".

And just like said @Pointy, the first parameter of "saveItem" and "getItem" should be a string.

By this way, you saved everything under "undefined" key and got everything under "undefined" key. Then, you only got the last saved value 4 and fourth times.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.