LocalStorage - Assign value to setItem then getItem to form field

Viewed 34

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.

2 Answers

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")
})

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"

I wasn't exactly sure what it was that you were asking because you seemed to demonstrate knowledge of using localStorage in your post.

Related