[英]How do you save multiple key value pairs to one cookie with JavaScript/jQuery?
I have a form with multiple checkboxes in it and when I click them, I want to add/remove the key-value pairs (name of the input + true/false) in one single cookie.我有一个包含多个复选框的表单,当我单击它们时,我想在一个 cookie 中添加/删除键值对(输入名称 + true/false)。
When I click on the checkboxes only the first pair gets shown in console.log.当我单击复选框时,只有第一对会显示在 console.log 中。
This is what I ended up with so far:这是我到目前为止的结果:
HTML: HTML:
<form class="form">
<input class="input" name="expert_id_1" type="checkbox" />
<input class="input" name="expert_id_2" type="checkbox" />
<input class="input" name="expert_id_3" type="checkbox" />
<input class="input" name="expert_id_4" type="checkbox" />
</form>
JS: JS:
function setCookie() {
var customObject = {};
var inputName = $('.input').attr('name');
customObject[inputName] = $('.input').prop('checked');
var jsonString = JSON.stringify(customObject);
document.cookie = 'cookieObject=' + jsonString;
console.log(jsonString);
}
function getCookie() {
var nameValueArray = document.cookie.split('=');
var customObject = JSON.parse(nameValueArray[1]);
$('.input').prop('checked') = customObject[inputName];
}
$('.input').each(function() {
$(this).on('click', function() {
if ($(this).is(':checked')) {
$(this).attr('value', 'true');
} else {
$(this).attr('value', 'false');
}
setCookie();
});
});
Your cookie is being overrided and it might only store the first checkbox info.您的 cookie 正在被覆盖,它可能只存储第一个复选框信息。 Also to set the prop value, you have to pass it as a second parameter.
同样要设置 prop 值,您必须将其作为第二个参数传递。
This should update the cookie when clicked and also be able to set the values from the cookie.这应该会在单击时更新 cookie,并且还可以设置 cookie 中的值。
function updateCookie($input) {
var cookieObject = getCookieObject();
var inputName = $input.attr('name');
cookieObject[inputName] = $input.attr('value');
var jsonString = JSON.stringify(cookieObject);
document.cookie = 'cookieObject=' + jsonString;
console.log(jsonString);
}
function setFromCookie(){
var cookieObject = getCookieObject();
for(var inputName in cookieObject)
if(cookieObject.hasOwnProperty(inputName))
$(`.input[name="${inputName}"]`).prop('checked', cookieObject[inputName]);
}
function getCookieObject() {
var nameValueArray = document.cookie.split('=');
var cookieObject = {};
if(nameValueArray.length >= 2)
cookieObject = JSON.parse(nameValueArray[1]);
return cookieObject;
}
$('.input').each(function() {
var $this = $(this);
$this.on('click', function() {
$this.attr('value', String($this.is(':checked')))
updateCookie($this);
});
});
Although I would recomend you to use a URLSearchParams object to encode and decode the parameters, since you are relying on the fact that "="
is not inside the JSON string.尽管我建议您使用URLSearchParams对象来编码和解码参数,因为您依赖于
"="
不在 JSON 字符串中的事实。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.