Zerh Ariel February 2016

Javascript - Can I display the value of a cookie in HTML?

I have a bootstrap website and I stock user information in cookies with the plugin JS-cookie.

Can I show the value of the cookie in the HTML with classic JS/Jquery or do I have to use a framework like Angular ?

EDIT :

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

So my code is, in the head page :

         <script>Cookies.set('money', '200', { expires: 7 });</script>

and in the body :

       <p> You have  <script>Cookies.get('money')</script> dollars </p>

Answers


Barmar February 2016

You don't just insert a script in the middle of HTML to get the result of a function. The script has to perform an operation to put a value into the DOM.

<p You have <span id="amount"></span> dollars </p>
<script>
var amount = Cookies.get('money');
document.getElementById('amount').textContent = amount;
</script>


threed February 2016

In native JavaScript, you can do the following. Note: this doesn't seem to work on Stackoverflow because of a security restriction, but it does seem to work in CodePen.

var arr = document.cookie.split(';'),
    cookies = {};
for(var i=0; i < arr.length; i++){
  var parts = arr[i].split('=');
  if(parts.length !== 2) continue;
  cookies[parts[0].trim()] = parts[1];
}
console.dir(cookies)

document.getElementById('out').textContent = cookies['myCookieKey'];
<div id="out"></div>

Update

Using the JS-Cookie code:

<p>You have <span id="amount"></span> dollars</p>

<script>
document.getElementById('amount').textContent = Cookies.get('money');
</script>

Post Status

Asked in February 2016
Viewed 2,843 times
Voted 5
Answered 2 times

Search




Leave an answer