Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checkboxes and localStorage

Tags:

javascript

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>
like image 576
TheCrazyTech Avatar asked Apr 02 '26 00:04

TheCrazyTech


1 Answers

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.com/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>
like image 100
Rando Shtishi Avatar answered Apr 04 '26 13:04

Rando Shtishi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!