If you are trying to store and load the state of a checkbox input using localStorage
, but the state is not being applied correctly, ensure you are properly retrieving and setting the checkbox state when the page loads. Here is an example to demonstrate this:
HTML :
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Checkbox State with localStorage</title> </head> <body> <input type="checkbox" id="myCheckbox"> Check me! <script src="script.js"></script> </body> </html>
JavaScript :
document.addEventListener("DOMContentLoaded", function() { const checkbox = document.getElementById('myCheckbox'); // Load the saved state from localStorage const savedState = localStorage.getItem('checkboxState'); if (savedState !== null) { checkbox.checked = JSON.parse(savedState); } // Save the state to localStorage whenever it changes checkbox.addEventListener('change', function() { localStorage.setItem('checkboxState', checkbox.checked); }); });
- Load State: When the page loads, the saved state of the checkbox is retrieved from
localStorage
. If there is a saved state, it is applied to the checkbox. - Save State: Whenever the checkbox state changes (checked/unchecked), the new state is saved to
localStorage
.
Leave a Reply