Preserve multiple checkboxes in local storage without erasing them

I have a form with a checkbox that I want to save the status of (true/false) to local storage when the form is submitted.

For example, if a user checks the box and submits the form, the value stored in local storage will be set to "true". However, I don't want this data to be overwritten if the user re-opens the app and submits the form again. If the user decides not to check the box during another session, the local storage values should be "true, false", and so on.

I believe using JSON.stringify would be useful but I'm unsure how to implement it here.

Below is my JavaScript code (using PhoneGap):

document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady() {
    document.getElementById("xbutton").addEventListener("click", saveCheck, false);
}

function saveCheck() {
    var checkbox = document.getElementById("MedA");
    localStorage.setItem("MedA", checkbox.checked);
}

HTML:

<form>
    <div id='medA'>
        <input type="checkbox" id="MedA" name="Med" value="A"> Medication A
    </div>
    <input id="xbutton" type="button" onClick="saveCheck()" value="Submit">
</form>

Answer №1

Next, here's the jQuery code snippet:

var ArrayA = [200];
localStorage.setItem("index",0);

function storeCheck(){

    if($('input[name="chk[]"]:checked')){
        ArrayA[localStorage.getItem("index")] = $('input[name="chk[]"]').val();
        localStorage.setItem("index",localStorage.getItem("index")+1);
        localStorage.setItem("ArrayA", JSON.stringify(ArrayA));
    }
}

To retrieve saved check from local storage, you can use the following function:

function retrieveSavedCheck(){

    var storedArrayA = JSON.parse(localStorage.getItem("ArrayA"));

    return storedArrayA;
}

Answer №2

To maintain the checkbox state when users submit a form without changing it, consider loading the state from localStorage:

document.addEventListener("DOMContentLoaded",onReady,false);

function onReady() {
  document.getElementById("checkbox").addEventListener("click",saveCheckboxState,false);
  document.getElementById("checkbox").checked = localStorage.getItem("isChecked");
}

function saveCheckboxState(){
  var checkboxElement = document.getElementById("checkbox");
  localStorage.setItem("isChecked", checkboxElement.checked);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript class errors due to undeclared variables

I'm currently facing challenges with implementing and understanding classes in JavaScript. My experimentation involves a simple app that I created with the objective of extracting names from a textarea, storing them in an array, and then performing va ...

Tips for redirecting JavaScript requests to the target server using curl on a server

Currently, I am running a crawler on my server and require the execution of JavaScript to access certain data on the target site that I want to crawl. I recently had a question about a different approach to this issue, but for now, I need help with the fol ...

React's memo and/or useCallback functions are not functioning as anticipated

Within my Home Component, there is a state called records, which I utilize to execute a records.map() and display individual RecordItem components within a table. function Home() { const [records, setRecords] = useState<Array<RecordType>>(l ...

Tips for Automatically Loading Dependencies in AngularJS

Currently, I am working on an Angular application where I am designing various widgets using HTML5. Here is a snippet of the code structure: <html ng-app> <div ng-controller="widget1"> </div> <div ng-controller="widget2"> ...

Error: authentication failed during npm installation due to an incorrect URL

After executing npm install @types/js-cookie@^2.2.0, an error occurred: npm install @types/js-cookie@^2.2.0 npm ERR! code E401 npm ERR! Unable to authenticate, need: Basic realm="https://pkgsprodsu3weu.app.pkgs.visualstudio.com/" npm ERR! A com ...

Transform the deserialized JSON string into a tree structure without utilizing a class

My JSON string looks like this: {"fields": "{\n \"CurrentPage\": 14,\n \"CurrentSubPageNo\": 18,\n \"IsFileUpload\": false,\n \"VisitedPages\& ...

Inscribe latitude from marker onto input field

Currently, I am working on a feature where markers are added to Google Maps API v3 by clicking on the map. Each marker then displays its coordinates in an info window. However, I am facing an issue with picking up the latitude and longitude values and inse ...

A guide on adding meta description in Sails JS version 1.0

Wondering how to add a meta description tag in a Sails JS version 1.0 application to improve SEO? Despite having a web app, Google's indexing isn't displaying the right information I want. The descriptions shown under the links are not clear eno ...

Leveraging Json.Net's ContractResolver alongside inner reference properties

During the development of our API, we encountered a need to filter out certain properties of a model that are not accessible to the requesting user. We managed to fulfill this requirement using Json.Net ContractResolver. public class ConverterContractRes ...

Exploring the Mechanism Behind the Successful String Interpolation of a Variable Imported in my Angular 2 Application

After making some modifications to my Angular 2 application, I encountered a situation where something started functioning properly sooner than I expected. This has left me puzzled about why it's working in its current state. Specifically, I have an a ...

Transmit array of javascript to server

I am currently trying to figure out how to send an array's content from my javascript to a file on my server. Despite searching online, I haven't been able to find a solution yet. If I have a server and want to save this array data in a file, ho ...

Changing the active class on Bootstrap nav tabs across pages

My website features a set of navigation tabs on the homepage that provide links for users to access more information. I want the site to automatically navigate to the corresponding tab on another page when a user clicks on the link. If you'd like to c ...

Why is my browser failing to show spaces in list text when using the SELECT tag?

While using IE7, I noticed that the options in my SELECT tag are displayed without the leading spaces in the text - it appears that the text is being trimmed. For instance, in the HTML code block provided below, even though options 1 to 3 have three spaces ...

Terminal detected a problem with the perl script

I'm currently experiencing an issue with one of our perl scripts that was running smoothly until last month. Can anyone provide assistance? An error message is being displayed: malformed JSON string, neither array, object, number, string or atom, at c ...

In what scenarios would JavaScript Promises skip both .catch and .then methods?

There's a question with countless possible answers, or perhaps a peek at my actual code is necessary for assistance. It may be that there is a single cause, or just a few causes, for the behavior I'm observing. The first question is: Which scenar ...

Unable to access variables beyond the function scope results in an undefined value

I'm currently working with an npm package that shortens URLs but I'm struggling because there isn't much documentation available. The package takes the "this.src" URL and shortens it, but when I try to use the "url" element in HTML, it retur ...

Error 500: Circular reference detected in JSON endpoint

Currently in the process of creating a JSON endpoint for objects (tickets). Here is the function I'm using: /** * @Route("/json/tickets", name="json_tickets") */ public function jsonTickets() { $encoders = [new XmlEncoder(), new JsonEncoder()] ...

CKEditor directive in AngularJS does not properly enforce the maxlength attribute in textarea

I am currently working on an AngularJS application with the CKEditor plugin. I have created a directive for CKEditor and everything seems to be functioning properly. However, I am facing an issue where I need to limit the character length to 50. I tried us ...

Circular Menu attached to Floating Action Button

Looking to design a Floating Action button that displays a circular menuhttps://i.sstatic.net/D3JOU.jpg Do you think it's achievable using solely css? ...

Setting a setTimeout function for a Vue function

Can clearTimeout be used for a setTimeout function assigned to a Vue Method? If yes, how can it be accomplished? methods: { timeoutController() { setTimeout(function() { this.controllerShown = false; }, 3000); ...