Cut costs by saving checkbox states in local storage

I have a JavaScript function that creates a checkbox and listens for a change event:

function test() {
    var a = document.getElementById('test');
    var b = document.createElement('input');
    b.type = 'checkbox';
    b.addEventListener( 'change', function() {
    if(this.checked) {
       //do something and save the state (checked)
    } else {
       //do something else and save the state(not checked)
    }
}

How can I ensure that the checkbox's state is saved to local storage after it has been appended?

Answer №1

When adding multiple checkboxes and needing to set their data separately, it's crucial to assign a unique ID to each one. This ensures that you can manipulate each checkbox individually. One way to manage this is by incrementing the IDs every time a new checkbox is appended.


//function for appending a new checkbox

var i = 0;
function appendCheckBox(){
    i++
    checkBoxId = 'checkbox' + i;
    document.getElementById('checkbox-container').innerHTML = `<input type="checkbox" id="${checkBoxId}" onclick="handleCheckBoxClick(this)"></input>`;
}

//function to handle checkbox click event, which should include logic to toggle checked/unchecked status

function handleCheckBoxClick(ev){
    var checkBoxId = ev.id;
    localStorage.setItem(checkBoxId, 'checked')
}

Answer №2

Here is a way to utilize :

Storing data :

localStorage.setItem('checkbox', b.checked);

Retrieving data :

var checkVal=localStorage.getItem('checkbox');

Answer №3

Some effort will be required on your part. The use of localStorage is not functional within a snippet here, but you can view a functioning example of the code provided at this JSFiddle link

localStorage.setItem("Checkboxes", "{}");
const showCurrentCheckboxStates = () => 
  document.querySelector("pre").textContent = `Checkboxes saved state ${
    JSON.stringify(JSON.parse(localStorage.getItem("Checkboxes")), null, " ")}`;
const saveCheckboxState = (val, id) => {
  localStorage.setItem("Checkboxes", 
      JSON.stringify({
        ...JSON.parse(localStorage.getItem("Checkboxes")),
        [`Checkbox ${id}`]: val })
      );
  showCurrentCheckboxStates();
};
const createCheckbox = id => {
  let cb = document.createElement('input');
  cb.type = 'checkbox';
  cb.dataset.index = id;
  cb.title = `Checkbox ${id}`;
  document.body.appendChild(cb);
  // save the initial state
  saveCheckboxState(0, id);
};

document.addEventListener("click", evt =>
  evt.target.dataset.index && 
    saveCheckboxState(+evt.target.checked, evt.target.dataset.index)
);

for (let i = 1; i < 11; i += 1) {
  createCheckbox(i);
}

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

What could be the reason for this script not functioning properly and...?

Here is some HTML code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" conte ...

Preventing typing during onKeyDown event in React/JavaScript and other languages

One of the reasons why I opt to use onKeyDown is because the language for typing is Korean. With multiple inputs on the page, my aim is to prevent users from typing more than 20 bytes. //this function calculates the byte length const getByteLength = (s,b ...

I am having trouble setting breakpoints in Google Chrome

For a while, I've been using Google Chrome to debug my JavaScript code without any issues. However, out of nowhere, I am no longer able to place breakpoints. When I click on the line number where I used to add breakpoints, nothing happens. Sometimes, ...

The favicon fails to appear properly when sharing the link on Instagram

Whenever I share my website link on Instagram, it shows an image that is not the one I want to appear. Oddly enough, when I send the URL through a text message, the Favicon displays correctly. How can I resolve this problem? https://i.sstatic.net/siQVs.pn ...

I am unable to modify the view page in CodeIgniter

I'm encountering difficulties when attempting to modify the view page within my code. Please note that I am utilizing AJAX. Within the controller function known as "insert_inventario", after saving information in the array_db, it undergoes a comparis ...

What is the best way to assign Reference Identification numbers to the orders?

Is there a way for me to obtain and attach the id reference to the order? I have retrieved the product and user ids. When I utilize my get method, it should retrieve all the details about the products and users. For instance, the data will display compreh ...

Why are static PropTypes used in ReactJS and do they offer any solutions or are they merely a recurring design choice?

While delving into the code base of a web application, I came across some static PropTypes that left me questioning their purpose and necessity. Here is a snippet of the code in question: static propTypes = { fetchCricketFantasyPlayers: PropTypes.fun ...

The Bootstrap Navbar-fixed-bottom div is covering up the JS rendered content due to an

The content on my main page container is being obscured by the content within this DIV: <div class="navbar navbar-fixed-bottom"></div> Below is the CSS from the GitHub project (bootstrap sass) // Code to fix top/bottom navbars when screen re ...

What is the reason why I am limited to loading only local resources for my index file?

I'm currently running a nodejs server and have implemented a login, signup, and menu feature on my website. Here is what my login UI looks like: https://i.sstatic.net/eg57R.png As for my signup page, it appears as follows: https://i.sstatic.net/qToQ ...

Unable to completely conceal the borders of Material UI Cards

Despite my efforts to blend the card with the background, I am still struggling with the tiny exposed corners. I've spent hours searching for a solution, but nothing seems to work. I've tried various methods such as adjusting the border radius in ...

Attempting to establish a connection with MongoDB through Realm

Exploring Realm and MongoDB for the first time has been an interesting journey for me. I began by following a helpful tutorial as a starting point for my project. Here is the link to my project structure on CodeSandbox The folder structure includes: src ...

Node.js throws an error with the message "Unexpected token *" while utilizing the robe

Currently, I'm working on a Node.js application where I'm attempting to utilize the node module named robe. Unfortunately, I encountered an error message when trying to launch the app: function* promiseToGenerator(promise) { ^ Error l ...

What steps can I take to detect errors when generating a MongoDB ObjectId in Node.js?

var selectedCriteria = Mongoose.Types.ObjectId(payloadData.skillId), If an incorrect Id is passed, the following error message will be displayed: Error: Uncaught error: Argument passed in must be a single string of 12 bytes or a string of 24 hex charac ...

Avoid unnecessary renders by only updating state if it has changed from the previous state

Is there a specific React lifecycle method that can trigger a re-render only when the updated state differs from the previous state? For instance, consider the code snippet below: class App extends Component { constructor() { super(); this.state ...

Typescript's Nested Type Assignments

Simply put, I'm making an API call and receiving the following data: { getUserInfo: { country: 'DE', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3c48594f487c59445d514c5059125f5351">[e ...

Is it ever considered safe to manually relocate a DOM node rendered by Vue? If so, when?

I am aware of the risks associated with manually manipulating DOM nodes rendered by a Vue component, such as: Vue overriding changes after another render Potential interference with Vue's patching algorithm My specific scenario involves wanting to m ...

The proper usage of middleware in vue-router

I've set up routes in Vue and added some middleware conditions before each route, but it's not functioning as expected. Below is the content of my router/index.js file: const token = computed(() => useAuthStore().token); // Main Router cons ...

Validation in AngularJS is limited to only accepting integers with the use of the

Can you help me with validating positive integer numbers using the ng-pattern attribute? Currently, I have this pattern: ^[0-9]{1,7}(\.[0-9]+)?$/, but it also allows decimal values. I want to restrict it to only accept whole numbers. ...

Is it possible to generate a PNG blob using binary data stored in a typed array?

I have a piece of binary data that is formatted as a PNG image. I am looking to convert it into a blob, generate a URL for the blob, and then showcase it as an image in various places where an image URL can be used, such as CSS. My initial approach invol ...

Is there a way to automatically load Moment.JS within Compound.JS?

Is it possible to make Moment accessible worldwide using the Compound framework with its module auto-loading feature? How can "moment" be included in the autoload array and used within the application? ...