Home > Enterprise >  LocalStorage - Assign value to setItem then getItem to form field
LocalStorage - Assign value to setItem then getItem to form field

Time:07-10

I am using a script that creates a value:

script

The last line is: getID = final_collected_id || '';

/script

Example: getID looks like: 123456789

I'd like to use localStorage.setItem and assign the value of getID

Not sure how this value is assigned as it is not using a var = getID but might be the fix?

Then, I would like to use the getItem and output in a form field:

Then use the clear()

I have a form with additional fields and some with HTML design and attempting to add the getID in a direct java-script didn't work.

I appreciate any help.

CodePudding user response:

KIC.

You can set the value by doing:

localStorage.setItem('ID', '1234');

and you can get the value by doing:

localStorage.getItem('ID');

then you can define your variable as:

const getID = localStorage.getItem('ID') || "1234"

Hope this helps. I wasn't exactly sure what it was that you were asking because you seemed to demonstrate knowledge of using localStorage in your post. Feel free to respond to my comment going further in-depth and I'll do the best I can to help out.

CodePudding user response:

My comments are in the comments.

var getID = 0;
getID  = 1234 || '';

// first check value is ok
console.log(getID)

// then store it under name "getID"
localStorage.setItem("getID", getID);

// get the value back (next time)
var value = localStorage.getItem("getID") || '';

// make the form have it
document.getElementById("my-input").value = value;

// if you have a clear button 
document.getElementById("my-button").addEventListener(function() {
  localStorage.removeItem("getID")
})
  • Related