Michael Schwartz Michael Schwartz - 4 months ago 20
Javascript Question

Use LocalStorage with Checkbox Checked by Default

Pen: http://codepen.io/anon/pen/YWaJaP?editors=0010

Fiddle: https://jsfiddle.net/qnLhtzss/

By default I want the checkbox checked, but if the user changes it I want it saved to what the user saved it as.

It saves the state when the user clicks on the link but by default the checkbox is not checked when it's suppose to be.

Can someone explain why this is not working?

HTML:

<input type="checkbox" id="changePrev" checked>
<label for="changePrev">Auto Update Preview</label>


JavaScript:

// Toggle Auto Update Preview
var checkedPrev = JSON.parse(localStorage.getItem("autoUpdate"));
var changePrev = document.getElementById("changePrev");
changePrev.checked = checkedPrev;

$("#changePrev").on("change", function() {
(this.checked) ? localStorage.setItem("autoUpdate", "true") : localStorage.setItem("autoUpdate", "false");
}).trigger("change");

Answer

The issue is that the first time the use navigates to the page

var checkedPrev = JSON.parse(localStorage.getItem("autoUpdate"));

will be null because there is no "autoUpdate" key present in the LocalStorage. This subsequently sets changePrev.checked = checkedPrev to null, and ultimately results in the checkbox becoming unchecked.

You can fix this by a simple null check on checkedPrev and defaulting to true if it was null.

// Toggle Auto Update Preview
var checkedPrev = JSON.parse(localStorage.getItem("autoUpdate"));
// If checkedPrev === null then the use has never been here before.
// Make checkedPrev default to true
checkedPrev = checkedPrev === null ? true : false;
var changePrev = document.getElementById("changePrev");
changePrev.checked = checkedPrev;

$("#changePrev").on("change", function() {
  (this.checked) ? localStorage.setItem("autoUpdate", "true") : localStorage.setItem("autoUpdate", "false");
}).trigger("change");
Comments