JSFiddle - React, Tailwind, and code Playground
HTML
<p>保存クリックでチェックをCOOKIEに保存したい。</p>
<div>
<label><input type="checkbox" name="chk_sample" value="apple">りんご</label>
<label><input type="checkbox" name="chk_sample" value="orange">みかん</label>
</div>
<div class="save">保存</div>
<script>
(function($){
$('body').on("click",'.save',function(){
$.cookie("chk_sample_selected_value")
var load_values = $.cookie("chk_sample_selected_value").split(",");
for(var i = 0; i < load_values.length; ++i){
load_values[i] = decodeURIComponent(load_values[i]);
}
$("input[type=checkbox][name=chk_sample]").each(function(){
this.checked = $.inArray(this.value, load_values) != -1;
});
});
})(jQuery);
</script>
CSS
p {
background: pink;
}
.save{
background: pink;
padding: 10px;
border-radius:10px;
width: 100px;
text-align: center;
cursor: pointer;
}
JavaScript
///ライブラリ「jquery.cookie.js」の中身全部
/*!
* jQuery Cookie Plugin v1.4.1
* https://github.com/carhartl/jquery-cookie
*
* Copyright 2006, 2014 Klaus Hartl
* Released under the MIT license
*/
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD (Register as an anonymous module)
define(['jquery'], factory);
} else if (typeof exports === 'object') {
// Node/CommonJS
module.exports = factory(require('jquery'));
} else {
// Browser globals
factory(jQuery);
}
}(function ($) {
var pluses = /\+/g;
function encode(s) {
return config.raw ? s : encodeURIComponent(s);
}
function decode(s) {
return config.raw ? s : decodeURIComponent(s);
}
function stringifyCookieValue(value) {
return encode(config.json ? JSON.stringify(value) : String(value));
}
function parseCookieValue(s) {
if (s.indexOf('"') === 0) {
// This is a quoted cookie as according to RFC2068, unescape...
s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
}
try {
// Replace server-side written pluses with spaces.
// If we can't decode the cookie, ignore it, it's unusable.
// If we can't parse the cookie, ignore it, it's unusable.
s = decodeURIComponent(s.replace(pluses, ' '));
return config.json ? JSON.parse(s) : s;
} catch(e) {}
}
function read(s, converter) {
var value = config.raw ? s : parseCookieValue(s);
return $.isFunction(converter) ? converter(value) : value;
}
var config = $.cookie = function (key, value, options) {
// Write
if (arguments.length > 1 && !$.isFunction(value)) {
options = $.extend({}, config.defaults, options);
if (typeof options.expires === 'number') {
var days = options.expires, t = options.expires = new Date();
t.setMilliseconds(t.getMilliseconds() + days * 864e+5);
}
return (document.cookie = [
encode(key), '=', stringifyCookieValue(value),
options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute,...