Javascript

Manuel0815

Newbie
Joined
Jun 12, 2021
Messages
3
Reaction score
1
I have a question. Hoe do i can store a variable into a cookie?
For example i have the function:

function log(){
var userinput = {
Name: document.getElementById('name').value
}
Var user = userinout.name;
}

Hoe can i store the 'user' variable into a cookie, and how can i automaticly fill this input from the user after reloading website into for example Forms?

Thx for your answers
 
I would suggest using this library:

https://github.com/js-cookie/js-cookie

It's quick and easy to use :

Code:
Cookies.set('foo', 'bar');
Cookies.get('name'); // => 'value'

Hope this helps.
 
Unfortunately JavaScript does not have a builtin convenience method for getting and setting cookies so you need to write your own or use a library.

Have a look at the following for examples on getting and setting a cookie: https://www.w3schools.com/js/js_cookies.asp

You can call getCookie('user') when you want to get the cookie value and then call setCookie to set it. If you want to store the entire userinput json object in the cookie then you need to convert it to a string before setting, and then JSON.parse the cookie value to convert it back to an object.

JavaScript:
function log() {
  var userinput = {
    name: document.getElementById('name').value
  }
  var user = userinout.name;
  setCookie('user', JSON.stringify(user));
}


// when page loads
var userinput = JSON.parse(getCookie('user'));
if (userinput && userinput.hasOwnProperty('name')) {
  document.getElementById('name').value = userinput.name;
}
 
You could also use localStorage for storing and retrieving data. Cookie is a bit frowned upon these days specially after GDPR happened. So, you can't use cookies (if you do it the right way that is) until the user has accepted the usage.

For an example, check this out, if you want to use localStorage.
Code:
https://html.spec.whatwg.org/multipage/webstorage.html

Here's a cookie vs localstorage comparison (and when to use which one)
Code:
https://stackoverflow.com/a/3220802/1437261
 
Back
Top