Cookie会记住复选框是否被选中吗?

huangapple go评论84阅读模式
英文:

Cookie remembers that a checkbox has been ticked?

问题

我正在寻找创建一个待办事项列表风格的网页,但我不希望用户必须登录才能记住他们已经完成的事项。这个清单有一个非常具体的用例,我不会详细介绍。

假设我有一个像下面这样的复选框列表:

待办事项:
[✔] 任务1
[ ] 任务2
[ ] 任务3

我已经勾选了任务1表示它已完成。

有没有办法设置一个cookie,这样当用户返回时,任务1仍然被选中,任务2和任务3仍然未选中?当任务2和任务3被不可避免地选中或取消选中时,这个cookie需要更新。

英文:

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 <input type="checkbox"> 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.

答案1

得分: 1

是的,我用HTML和JavaScript成功解决了这个问题:

<!DOCTYPE html>
<html>
<head>
  <title>待办事项列表</title>
</head>
<body>
  <h1>待办事项:</h1>
  <label><input type="checkbox" id="task1"> 任务1</label><br>
  <label><input type="checkbox" id="task2"> 任务2</label><br>
  <label><input type="checkbox" id="task3"> 任务3</label><br>
  <script src="script.js"></script>
</body>
</html>
// 设置cookie的函数
function setCookie(cname, cvalue) {
  var d = new Date();
  d.setTime(d.getTime() + (30 * 24 * 60 * 60 * 1000)); // 30天过期
  var expires = "expires=" + d.toUTCString();
  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

// 根据名称获取cookie的函数
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 "";
}

// 更新复选框和cookie状态的函数
function updateStatus(taskId) {
  var taskElement = document.getElementById(taskId);
  var isChecked = taskElement.checked ? "true" : "false";
  setCookie(taskId, isChecked);
}

// 从cookie初始化复选框状态的函数
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);
    });
  }
}

// 页面加载时调用初始化函数
initializeStatus();

这段代码的作用是设置和获取cookie。当复选框被点击时,它的状态会被存储在一个cookie中。当页面重新加载时,复选框的状态会从cookie中读取并相应地恢复。

英文:

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

&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
  &lt;title&gt;Todo List&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
  &lt;h1&gt;To do:&lt;/h1&gt;
  &lt;label&gt;&lt;input type=&quot;checkbox&quot; id=&quot;task1&quot;&gt; Task 1&lt;/label&gt;&lt;br&gt;
  &lt;label&gt;&lt;input type=&quot;checkbox&quot; id=&quot;task2&quot;&gt; Task 2&lt;/label&gt;&lt;br&gt;
  &lt;label&gt;&lt;input type=&quot;checkbox&quot; id=&quot;task3&quot;&gt; Task 3&lt;/label&gt;&lt;br&gt;
  &lt;script src=&quot;script.js&quot;&gt;&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
// 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 = &quot;expires=&quot; + d.toUTCString();
  document.cookie = cname + &quot;=&quot; + cvalue + &quot;;&quot; + expires + &quot;;path=/&quot;;
}

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

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

// Function to initialize the checkbox statuses from cookies
function initializeStatus() {
  for (var i = 1; i &lt;= 3; i++) {
    var taskId = &quot;task&quot; + i;
    var cookieValue = getCookie(taskId);
    if (cookieValue === &quot;true&quot;) {
      document.getElementById(taskId).checked = true;
    }
    document.getElementById(taskId).addEventListener(&quot;change&quot;, 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

答案2

得分: 0

如果您只需要在浏览器中使用该值,可能更简单的方法是使用本地存储(localstorage),而cookie则用于在服务器端也能读取。

设置值的方法:

localStorage.setItem("checkbox1", value)

读取值的方法:

const checkbox1Value = localStorage.getItem('checkbox1') ? Boolean(localStorage.getItem('checkbox1')) : false
英文:

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(&quot;checkbox1&quot;, value)

To read the value:

const checkbox1Value = localStorage.getItem(&#39;checkbox1&#39;) ? Boolean(localStorage.getItem(&#39;checkbox1&#39;)) : false

huangapple
  • 本文由 发表于 2023年8月9日 16:28:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76865908.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定