0

I'm looking to create a to-do list style webpage but I don't want users to have to sign in to remember things they've ticked off. Very specific use case for this checklist which I won't get into.

So, let's say I have a check list like so:

To do:
[✔] Task 1
[ ] Task 2
[ ] Task 3

I've ticked Task 1 to say that it's complete.

Is there a way I can set a cookie so when the user returns, Task 1 is still checked and Task 2 and 3 are still unchecked? This would need to update when Task 2 and Task 3 are inevitably checked or unchecked.

DoMx
  • 41
  • 1
  • 7
  • 1
    Does this answer your question? [Getting a checkbox to write a JavaScript cookie](https://stackoverflow.com/questions/11801042/getting-a-checkbox-to-write-a-javascript-cookie) – Natrium Aug 09 '23 at 08:35
  • 1
    Depending on context, you may also wish to look into [local storage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage). See a comparison [here](https://stackoverflow.com/a/3220802/1371131). – Dennis Hackethal Aug 09 '23 at 08:36

2 Answers2

1

Yes, I managed to solve it with HTML & Javascript:

<!DOCTYPE html>
<html>
<head>
  <title>Todo List</title>
</head>
<body>
  <h1>To do:</h1>
  <label><input type="checkbox" id="task1"> Task 1</label><br>
  <label><input type="checkbox" id="task2"> Task 2</label><br>
  <label><input type="checkbox" id="task3"> Task 3</label><br>
  <script src="script.js"></script>
</body>
</html>
// Function to set a cookie
function setCookie(cname, cvalue) {
  var d = new Date();
  d.setTime(d.getTime() + (30 * 24 * 60 * 60 * 1000)); // 30 days expiry
  var expires = "expires=" + d.toUTCString();
  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

// Function to get a cookie by name
function getCookie(cname) {
  var name = cname + "=";
  var ca = document.cookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

// Function to update checkbox and cookie status
function updateStatus(taskId) {
  var taskElement = document.getElementById(taskId);
  var isChecked = taskElement.checked ? "true" : "false";
  setCookie(taskId, isChecked);
}

// Function to initialize the checkbox statuses from cookies
function initializeStatus() {
  for (var i = 1; i <= 3; i++) {
    var taskId = "task" + i;
    var cookieValue = getCookie(taskId);
    if (cookieValue === "true") {
      document.getElementById(taskId).checked = true;
    }
    document.getElementById(taskId).addEventListener("change", function() {
      updateStatus(this.id);
    });
  }
}

// Call the initialize function when the page loads
initializeStatus();

What this does is to set and get cookies. When a checkbox is clicked, its status is stored in a cookie. When the page is reloaded, the checkboxes statuses are read from the cookies and restored accordingly

MaikeruDev
  • 1,075
  • 1
  • 19
  • 1
    Luckily I had such a code snippet in one of my older projects so I just needed to change the input fields to checkboxes ^^ – MaikeruDev Aug 09 '23 at 08:36
  • 1
    You're a lifesaver, this is exactly what I was after! – DoMx Aug 09 '23 at 09:13
  • Hey MaikeruDev, if I wanted say 93 tasks, would I just need to replace `(var i = 1; i <= 3; i++) {` with `(var i = 1; i <= 93; i++) {` ? – DoMx Aug 09 '23 at 11:07
  • 1
    Yes! Your loop will be: for (var i = 1; i <= 93; i++). Also don't forget to numerate your input id's correctly from task1 to task93 – MaikeruDev Aug 09 '23 at 11:10
  • Sorry to bug you but I have a button for clear all using `document.querySelector('button').addEventListener('click', uncheckAll)` but that doesn't update the cookie. Do you know what I'm missing? – DoMx Aug 09 '23 at 11:31
  • No worries! Yeah you also need to delete all the cookies with ur uncheckAll function. I made some code in here assuming you still have the 93 checkboxes. https://pastebin.com/BKvQdaia Let me know if this worked – MaikeruDev Aug 09 '23 at 11:37
  • 1
    Ah, that makes WAY more sense than what I was trying ha. Thank you so much, you're a god send. Everything working as I wanted. – DoMx Aug 09 '23 at 11:43
  • You're welcome bud – MaikeruDev Aug 09 '23 at 11:45
0

If you only need the value in the browser it might be simpler to use localstorage, cookies are intended to be read also on server side.

To set the value:

localStorage.setItem("checkbox1", value)

To read the value:

const checkbox1Value = localStorage.getItem('checkbox1') ? Boolean(localStorage.getItem('checkbox1')) : false
Nicolas
  • 310
  • 2
  • 11
  • The issue is not they are intended to be read server-side - cookies+javascript is fine - but some browsers limit the size of cookies. Hence localstorage does make more sense. – symcbean Aug 09 '23 at 08:44