Save Checkbox State to LocalStorage – JavaScript and JQuery Example

You can save your JavaScript variables to browser localStorage. They are saved in the client’s web browser until user decides to “Clear recent history”.
Live demo allows you to see how the checkbox state is saved – even if you reload the page or close your browser.
I addition to learning localStorage and checkboxes, this tutorial touches some key concepts.

  • read source code in the order it’s run (not top down)
  • work in the smallest testable parts (test manually, validate html, check F12 console)
  • create separate working examples of each feature
  • search for documentation (“mdn input”, Stackoverflow, “jquery click”)
  • try your code interactively in F12 console

Hello World

All programs start with a “Hello World”. For this page, we must test HTML, JavaScript and jQuery. Write the web page

$ nano index.html

This hello world should have just HTML 5 skeleton, jQuery library and the main function called when document has loaded. JQuery library is the compressed, minified, production, version 3 from code.jquery.com/.

<!doctype html>
<html lang="en">
	<head>
		<title>Hello Tero's Checkbox and LocalStorage</title>
		<meta charset='utf-8'>
	</head>
	<body>
		<h1>Hello Tero's Checkbox and LocalStorage</h1>
		<p id="msg"></p>
		<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
		<script>
			function onReady() {
				$("#msg").text("Loaded.");
			}
			$(document).ready(onReady);
		</script>
	</body>
</html>

To test, open the file in Firefox or other browser. Static HTML obviously works when you can see the text in your browser.
If you can’t remember how HTML works, check my short HTML 5 skeleton and search the web for any tag you need + mdn (Mozilla Developer Network). For example, search mdn input.
JavaScript and jQuery write a message “Loaded” to page. If you can see the word “Loaded” under h1, jQuery is working.

Validate HTML

To validate HTML, use validator.w3.org. Right click, view source, copy. Go to validator.w3.org, “Direct input” tab, paste your code, click “Check”. Keep fixing it until you get the green “Document checking completed. No errors or warnings to show.”.
You should keep your HTML valid. After each new feature, validate and fix your code so that it’s always valid HTML. If something breaks, it often only makes sense to fix other things once the HTML is valid.

F12 Console for JavaScript

JavaScript (and it’s jQuery library) can log errors to F12 console.
Open your page in Firefox, press F12 to open developer console, open “Console” tab. There should be no errors related to your program.
Note that some Firefox addons can print errors to console, so if the error is really weird, verify that it actually comes from your program.
You can use console.log to print messages to F12 console.

Add a Form

Add a simple, static HTML form.

<form>
	<label for="box">Tero's CheckBox</label>
	<input type="checkbox" id="box">
</form>

We can check and uncheck the box, but the form does nothing else. Remember to validate HTML.

Read CheckBox from jQuery

Let’s add a JavaScript program to tell us if the box is checked on

function onClickBox() {
  $("#msg").text("Checkbox is checked: "+$("#box").is(":checked") );
}
function onReady() {
  $("#msg").text("Loaded.");
  $("#box").click(onClickBox);
}
$(document).ready(onReady);

Keep F12 console open while playing with JavaScript, so you can see any errors.

Read the Program in Execution Order

Programs should be read in the order they are run. Not top down.
First, the web page is fully loaded. The callback to onReady is executed.

$(document).ready(onReady);

Function onReady() is called

function onReady() {
  $("#msg").text("Loaded.");
  $("#box").click(onClickBox);
}

Contents of p tag with id “msg” are changed to “Loaded.”.
A new callback is set: The input tag with id “box” is now ready to react to click event. The callback function, onClickBox, is not run yet.
A user clicks the checkbox, so a click event is sent to id box. Only now the function onClickBox is run.

function onClickBox() {
  $("#msg").text("Checkbox is checked: "+$("#box").is(":checked") );
}

The status of input id box is checked. If it’s checked, the code returns boolean true. If unchecked, it returns boolean false.

$("#box").is(":checked")

This result (“true” or “false”) is concatenated to some text “Checkbox is checked”. Finally, the contents of p tag with id “msg” are changed to this string. For example, “Checkbox is checked: true” when there is a check in the box.
Click the checkbox a couple of times to test that the text changes correctly between true and false.
We can now read a checkbox with JavaScript and jQuery. Just like with “hello world”, now is a good time to copy this working code as a separate file, with name explaining the purpose of file. For example: “read-checkbox-with-jquery-working.html”.

Check and Uncheck with jQuery

Let’s check and uncheck the box with jQuery. In F12 console, try

$("#box").prop('checked', false);

The box is unchecked.

$("#box").prop('checked', true);

The box is checked.
Now that you can check and uncheck the box with jQuery, you should write a separate web page to test just this. This is left as an exercise for the reader.
How can I know how to do this? Using a web search engine, such as Google or DuckDuckGo. The answer is the first hit when searching jquery set checkbox and the answer is the highest voted answer in StackOverflow.

Save to LocalStorage

You can save data to client’s web browser with LocalStorage. The data is saved between sessions, even if web browser is closed and opened again. Data is lost when user chooses to “Clear recent history”.
We can search “mdn localstorage” for the reference documentation and example, then test with F12 console.

localStorage.setItem("who", "Tero");
undefined
localStorage.getItem("who");
"Tero"

You should write this a a separate web page. This is left as an exercise for the reader.

Checkbox State to LocalStorage

Let’s combine all the programs to final version. We’ll write a program that remembers the checkbox state between page reloads and browser sessions. Even if you reload the page, the box will stay check or unchecked, however you left it.
A new version of the program

function onClickBox() {
 let checked=$("#box").is(":checked");
 localStorage.setItem("checked", checked);
 $("#msg").text("Checkbox is checked: "+$("#box").is(":checked") );
}
function onReady() {
 $("#msg").text("Loaded.");

 let checked="true"==localStorage.getItem("checked");
 $("#box").prop('checked', checked);
 $("#box").click(onClickBox);
}
$(document).ready(onReady);

A look at the changes in the same order as the program runs
First, onReady() is called.
We read the status of localStorage item “checked”. It can be “true”, “false” or not defined.
As an added complication, it’s not boolean in localStorage, it’ a string. We can test if it’s a string that says “true”. The result of this check is a boolean value, true or false.

"true"==localStorage.getItem("checked");

This result, a boolean true or false, is then saved to a new variable “checked”. As we declare this variable inside the block “{ … }” with “let” keyword, it will only exist inside this block.
For example, if the result of the comparison was true, it becomes

let checked=true;

Pay attention to the two totally different, but similar looking constructs.

  • Value assingment “=”. E.g. “a=42” means “a is assigned value 42”.
  • Comparison “==”. E.g. “x==2” means “x equals 2”. The result of this comparison is boolean true or false. By itself, comparison “x==2” does not store the value anywhere.

When user clicks the box, we test if the box is checked (boolean true or false). The result is saved to new, local variable “checked”. This is a different variable from the “checked” in another block.
Now we save the check status to localStorage.

localStorage.setItem("checked", checked);

The Complete Program

Live demo allows you to see how the checkbox state is saved – even if you reload the page or close your browser.

<!doctype html>
<html lang="en">
	<head>
		<title>Hello Tero's Checkbox and LocalStorage</title>
		<meta charset='utf-8'>
	</head>
	<body>
		<h1>Hello Tero's Checkbox and LocalStorage</h1>
		<p id="msg"></p>
		<form>
			<label for="box">Tero's CheckBox</label>
			<input type="checkbox" id="box">
		</form>
		<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
		<script>
			function onClickBox() {
				let checked=$("#box").is(":checked");
				localStorage.setItem("checked", checked);
				$("#msg").text("Checkbox is checked: "+$("#box").is(":checked") );
			}
			function onReady() {
				$("#msg").text("Loaded.");
				let checked="true"==localStorage.getItem("checked");
				$("#box").prop('checked', checked);
				$("#box").click(onClickBox);
			}
			$(document).ready(onReady);
		</script>
	</body>
</html>

You can test it by checking the box, then reloading the page. The checkmark stays. Uncheck it and reload. The box stays unchecked.
You can now save checkbox state to localStorage.
This article has been updated with some additional explanations.

Posted in Uncategorized | Tagged , , , , , , , , , , | Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *