Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Zergham Choudhary
3,187 PointsHow to set and create a cookie from an ID element using javascript
I have a problem. I tried to set and create a cookie using an ID element. So when it sets a cookie from that ID and what ever is contained in that Id, it will display ona different HTML page. Now I did do something which does work create the cookie but it doesnt actualy set it so it appears on a different HTML page. The code is :
function createcookie(){ //Creating a cookie function
var fn = document.getElementById("total-cost").innerHTML;
document.cookie = fn;
alert(document.cookie);
}
Above is where i used a onlick function called "createcookie" and when user clicks on that button it gets the element ID "total-cost" (which is the price of an item) and it displays it as an alert box. Now for some reason this doesnt not work. I have tried to research on what the issue could be but can not find anything.
function showcookie(){
document.getElementById("price").innerHTML = ("You Paid - " + document.cookie);// shows cookie with in the element id "price", as a text.
}
The above code is the show cookie. So when the user opens the other HMTL page the cookie is shown as a text with onload.
This too doesnt work becasue its doesnt not seem to create the cookie and display it in the alert box.
1 Answer
Craig Watson
27,930 PointsHi,
Have you considered HTML Local Storage, I use it when I can rather than cookies.
Very simple to implement as well, I would suggest putting the code between two script tags in the header using a window.onload as well this fires the code straight away in case elements need to be hidden based on the condition you set.
You can edit them once created as well.
If you would like an example just let me know I will get you a code snippet I used.
Craig