最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Checkboxes and localStorage - Stack Overflow

programmeradmin2浏览0评论

I have a list of tasks if you will and I am trying to create checkboxes that persist next to each when I go back to the page but closing the browser or hard refresh kills my selections. I have found code for saving a single checkbox but how do I iterate through the different boxes and keep them next time I enter? It seems like a really simple process but I am super-new to javascript... I could do this easily in vbscript but I would like it to work everywhere and not just IE!

New to all this so be gentle please.

<input type="checkbox" id="whatever-1" />This task
<input type="checkbox" id="whatever-2" />This task
<input type="checkbox" id="whatever-3" />This task
<input type="checkbox" id="whatever-4" />This task
<input type="checkbox" id="whatever-5" />This task
<input type="button" value="Save" onclick="save();" />
// then enter variation of the code I found here
<script >
  function save() {
    //enter iteration sequence
    var checkbox = document.getElementById("box");
    localStorage.setItem("box", checkbox.checked);
  }

//for loading...
var checked = JSON.parse(localStorage.getItem("box"));
document.getElementById("box").checked = checked; <
/script>

I have a list of tasks if you will and I am trying to create checkboxes that persist next to each when I go back to the page but closing the browser or hard refresh kills my selections. I have found code for saving a single checkbox but how do I iterate through the different boxes and keep them next time I enter? It seems like a really simple process but I am super-new to javascript... I could do this easily in vbscript but I would like it to work everywhere and not just IE!

New to all this so be gentle please.

<input type="checkbox" id="whatever-1" />This task
<input type="checkbox" id="whatever-2" />This task
<input type="checkbox" id="whatever-3" />This task
<input type="checkbox" id="whatever-4" />This task
<input type="checkbox" id="whatever-5" />This task
<input type="button" value="Save" onclick="save();" />
// then enter variation of the code I found here
<script >
  function save() {
    //enter iteration sequence
    var checkbox = document.getElementById("box");
    localStorage.setItem("box", checkbox.checked);
  }

//for loading...
var checked = JSON.parse(localStorage.getItem("box"));
document.getElementById("box").checked = checked; <
/script>
Share Improve this question asked Jan 31, 2020 at 12:26 TheCrazyTechTheCrazyTech 513 bronze badges 3
  • 3 Wele to SO. Why not try something? You're currently dealing with only one box. Your ment even points to what you need to do - "enter iteration sequence". That is, you need to iterate over the checkboxes in a loop and build up a collection of values to save. – Mitya Commented Jan 31, 2020 at 12:29
  • You can do a for loop and do `document.getElementById("whatever-" +i) etc. – GaloisGirl Commented Jan 31, 2020 at 12:29
  • Are you trying to use localStorage in pages loaded from a local driver using the file:// protocol? This doesn't work in Microsoft browsers, IE or Edge which only support localStorage in pages from a server. It does work in Chrome or Firefox that I know of. – traktor Commented Jan 31, 2020 at 12:33
Add a ment  | 

4 Answers 4

Reset to default 5

To retrieve all elements you can use document.querySelectorAll and pass as argument the filter that will do the job. In this case you want to retrieve all htlm elements that have the type attribute value equals to checkbox. After the retrieval of all elements that have type="checkbox", you should traverse all elements of list. And for each element you should store the id of checkbox as key and the checked of the checkbox asvalue in localstorage.

Below is the code:

    <script>
        save = function(){
            var list = document.querySelectorAll(`[type*="checkbox"]`);
            list.forEach( el => {
                localStorage.setItem(el.id, el.checked);
                console.log(el.id,el.checked);
            })

        }
    </script>

And below is the code for updating the checkboxes with value we stored in localstorage.

            var list = document.querySelectorAll(`[type*="checkbox"]`);
            list.forEach( el => {
            var checked = JSON.parse(localStorage.getItem(el.id));
            document.getElementById(el.id).checked = checked;
            });

If you want to use cookie to store the information instead of local storage. Link for more information: https://www.guru99./cookies-in-javascript-ultimate-guide.html.


function createCookie(cookieName, cookieValue, daysToExpire) {
    var date = new Date();
    date.setTime(date.getTime() + (daysToExpire * 24 * 60 * 60 * 1000));
    document.cookie = cookieName + "=" + cookieValue + "; expires=" + date.toGMTString();
}

function accessCookie(cookieName) {
    var name = cookieName + "=";
    var allCookieArray = document.cookie.split(';');
    for (var i = 0; i < allCookieArray.length; i++) {
        var temp = allCookieArray[i].trim();
        if (temp.indexOf(name) == 0)
            return temp.substring(name.length, temp.length);
    }
    return "";
}

VERSION WITH LOCAL STORAGE

<html>
<head>
</head>
<body>
    <div>
        <input type="checkbox" id="whatever-1" />This task
        <input type="checkbox" id="whatever-2" />This task
        <input type="checkbox" id="whatever-3" />This task
        <input type="checkbox" id="whatever-4" />This task
        <input type="checkbox" id="whatever-5" />This task
        <input type="button" value="Save" onclick="save();" />
    </div>
        <script>
            window.onload= function(){
                    var list = document.querySelectorAll(`[type*="checkbox"]`);
                    list.forEach( el => {
                        var checked = JSON.parse(localStorage.getItem(el.id));
                        document.getElementById(el.id).checked = checked;
                    });
            }
            save = function(){
            var list = document.querySelectorAll(`[type*="checkbox"]`);
            list.forEach( el => {
                localStorage.setItem(el.id, el.checked);
                console.log(el.id,el.checked);
            })

        }
    </script>
</body>
</html>

VERSION WITH COOKIE

<html>
<head>
</head>
<body>
    <div>
        <input type="checkbox" id="whatever-1" />This task
        <input type="checkbox" id="whatever-2" />This task
        <input type="checkbox" id="whatever-3" />This task
        <input type="checkbox" id="whatever-4" />This task
        <input type="checkbox" id="whatever-5" />This task
        <input type="button" value="Save" onclick="save();" />
    </div>
        <script>
            window.onload= function(){
                    var list = document.querySelectorAll(`[type*="checkbox"]`);
                    list.forEach( el => {
                        var checked = JSON.parse(accessCookie(el.id));
                        document.getElementById(el.id).checked = checked;
                    });
            }
            save = function(){
                var list = document.querySelectorAll(`[type*="checkbox"]`);
                list.forEach( el => {
                    createCookie(el.id, el.checked,1);//1 is the day to expire
                    console.log(el.id,el.checked);
                })
            }
            function createCookie(cookieName, cookieValue, daysToExpire) {
                var date = new Date();
                date.setTime(date.getTime() + (daysToExpire * 24 * 60 * 60 * 1000));
                document.cookie = cookieName + "=" + cookieValue + "; expires=" + date.toGMTString();
            }

            function accessCookie(cookieName) {
                var name = cookieName + "=";
                var allCookieArray = document.cookie.split(';');
                for (var i = 0; i < allCookieArray.length; i++) {
                    var temp = allCookieArray[i].trim();
                    if (temp.indexOf(name) == 0)
                        return temp.substring(name.length, temp.length);
                }
                return "";
            }
    </script>
</body>
</html>

Just pass a different id in to document.getElementById. Make sure to use a different key for localStorage.setItem so you don't overwrite a different value.

var checkbox = document.getElementById("whatever-1");
localStorage.setItem("whatever-1", checkbox.checked);
var checked = JSON.parse(localStorage.getItem("whatever-1"));
document.getElementById("whatever-1").checked = checked;

You could do this individually for each item or you could get all the elements of a specific class. Then loop through the elements and use their id as the local storage key.


Alternatively you could use a for loop and loop for as many items as you wish to save

On every save you can create an object with checkbox identification and values, save t in localStorage, on reloading, get the the whole object by a single key, parse it, loop through and set values

function save() {
  //enter iteration sequence
  var checkboxes = document.querySelectorAll("input[type=checkbox]");
  var obj = {};
  for (i = 0; i < checkboxes.length; i++) {
    obj[checkboxes[i].id] = checkboxes[i].checked
  }
  localStorage.setItem("box", JSON.stringify(obj));
}

//for loading...
var checkboxesValues = JSON.parse(localStorage.getItem("box"));
Object.keys(checkboxesValues).map(key => document.getElementById(key).checked = checkboxesValues[key]);

Your code works well too if you pass right id's of inputs but there is an issue with it that for each and every input you have to add there variable you also can use for loop for that.

Your code with fixing script

<input type="checkbox" id="whatever-1" />This task
<input type="checkbox" id="whatever-2" />This task
<input type="button" value="Save" onclick="save();" />


<script>
  function save() {
    var checkbox = document.getElementById("whatever-1");
    localStorage.setItem("whatever-1", checkbox.checked);
    var checkbox2 = document.getElementById("whatever-2");
    localStorage.setItem("whatever-2", checkbox2.checked);
  }

var checked = JSON.parse(localStorage.getItem("whatever-1"));
document.getElementById("whatever-1").checked = checked; 

var checked = JSON.parse(localStorage.getItem("whatever-2"));
document.getElementById("whatever-2").checked = checked; 
</script>

发布评论

评论列表(0)

  1. 暂无评论