Persist Checkbox States with HTML5 Local Storage in Google Apps Script
Persist Checkbox States with HTML5 Local Storage in Google Apps Script

Store and Retrieve Checkbox Selections Using Local Storage in Google Apps Script Web App

Learn to use HTML5 local storage to easily save and retrieve checkbox states across pages in Google Apps Script web apps.6 min


Keeping track of user choices across different pages is a common struggle many developers encounter when creating multi-page applications. When working with Google Apps Script web apps, you may find it challenging to maintain checkbox selections as the user navigates between multiple pages.

Fortunately, HTML5 comes with built-in local storage, a simple and effective way to store data locally within a user’s browser. Unlike sessions, local storage helps you reliably retain user selections between pages—even if they refresh or close their browser tabs.

In this tutorial, I’ll guide you step-by-step through creating and implementing local storage to save and retrieve checkbox selections in your Google Apps Script web application.

Creating HTML Elements for Checkbox Selections

Let’s begin by creating two simple HTML pages: one for selecting sports, and another for picking favorite hobbies.

On the first page (“sports”), you’ll display two simple checkboxes: “Cricket” and “Football”:


<!-- First page: Sports Selection -->
<label><input type="checkbox" id="cricket"> Cricket</label>
<label><input type="checkbox" id="football"> Football</label>

<button id="nextPage">Go to Hobbies Selection</button>

Your second page (“hobbies”) contains checkboxes for “Singing” and “Dancing”:


<!-- Second page: Hobbies Selection -->
<label><input type="checkbox" id="singing"> Singing</label>
<label><input type="checkbox" id="dancing"> Dancing</label>

<button id="submitData">Submit Selections</button>

These HTML snippets provide users clear options and a button to continue their navigation journey, making the app intuitive and user-friendly.

JavaScript: Saving Checkbox States Using Local Storage

Now let’s handle the real magic—saving checkbox states. You’ll utilize the straightforward localStorage API provided by modern browsers.

Saving Checkbox Selections on the First Page:

When the user clicks to go to the next page, we store their checkbox selections:


document.getElementById("nextPage").addEventListener("click", function() {
  const cricketChecked = document.getElementById("cricket").checked;
  const footballChecked = document.getElementById("football").checked;

  localStorage.setItem("cricket", cricketChecked);
  localStorage.setItem("football", footballChecked);

  // Navigate to hobbies.html page
  window.location.href = "<?= ScriptApp.getService().getUrl(); ?>?page=hobbies";
});

In this snippet, localStorage.setItem() saves the user’s selection as key-value pairs. Later, you can easily retrieve these saved checkbox states on the following pages.

Retrieving Checkbox Selections on the Second Page:

On your second page, you’ll fetch these saved items from local storage to review or process:


document.addEventListener("DOMContentLoaded", function() {
  const cricket = localStorage.getItem("cricket") === "true";
  const football = localStorage.getItem("football") === "true";

  console.log("Sport Selections:", { cricket, football }); // For debugging purposes
});

document.getElementById("submitData").addEventListener("click", function() {
  const singingChecked = document.getElementById("singing").checked;
  const dancingChecked = document.getElementById("dancing").checked;

  localStorage.setItem("singing", singingChecked);
  localStorage.setItem("dancing", dancingChecked);

  // Optionally, send data to server or Google Sheet
  google.script.run.saveSelectionData({
    cricket: localStorage.getItem("cricket"),
    football: localStorage.getItem("football"),
    singing: singingChecked,
    dancing: dancingChecked
  });

  alert("Selections submitted successfully!");
});

By using simple event listeners and standard JavaScript methods—like localStorage.getItem()—you effortlessly pull the user’s previously stored data and blend it into your application experience.

Implementing Server-Side Functionality with Google Apps Script

You’ll also leverage Google Apps Script’s HTML Service capabilities to manage the page flow and store user selections permanently in a Google Sheet.

Here’s a basic structure for managing page requests inside your main server-side Apps Script (gs) file:


// Server-side code (Google Apps Script)

function doGet(e) {
  const page = e.parameter.page;
  
  if (page === "hobbies") {
    return HtmlService.createTemplateFromFile("hobbies").evaluate();
  }
  
  return HtmlService.createTemplateFromFile("sports").evaluate();
}

// Function to save checkbox data to Google Sheets
function saveSelectionData(data) {
  const ss = SpreadsheetApp.openById("YOUR_SPREADSHEET_ID").getSheetByName("Selections");
  ss.appendRow([
    new Date(),
    data.cricket,
    data.football,
    data.singing,
    data.dancing
  ]);
}

In this example:

  • doGet() serves as your entry point for web requests. It loads the appropriate HTML file based on a URL parameter.
  • saveSelectionData() appends checkbox selection data directly into a Google Sheet, along with a timestamp.

Make sure you replace YOUR_SPREADSHEET_ID with your actual Google Sheet ID. Want more insights into working with JavaScript in Google Apps Script? Check out more in-depth articles in my JavaScript tutorials.

Why Use Local Storage for Data Persistence?

Local storage empowers your apps by smoothly handling small data operations without involving the backend every single time. Imagine building a long multi-step form—losing user input halfway through would be frustrating. With local storage, even if someone accidentally reloads, or navigates away temporarily, their previous selections remain as is, significantly improving user experience.

Learning to utilize local storage alongside Google Apps Script will significantly enhance your ability to build robust, interactive web apps that users genuinely enjoy. It also lowers server load, as every checkbox selection doesn’t necessarily require immediate backend processing. Only finalized data may need server-side confirmation—like sending to a Google Sheet or database.

A Few Final Tips

  • Always consider privacy when using local storage. Don’t save sensitive user information this way.
  • Use browser development tools to inspect your local storage contents easily. Check out this helpful resource on Chrome DevTools Local Storage.
  • Data stored in local storage persists indefinitely, unless explicitly cleared. You might implement cleanup strategies or prompt users accordingly.

Now that you’ve seen it in action, the possibilities for enhancing your Google Apps Script web apps seem endless. How about implementing local storage today and seeing how it improves your next web project?


Like it? Share with your friends!

Shivateja Keerthi
Hey there! I'm Shivateja Keerthi, a full-stack developer who loves diving deep into code, fixing tricky bugs, and figuring out why things break. I mainly work with JavaScript and Python, and I enjoy sharing everything I learn - especially about debugging, troubleshooting errors, and making development smoother. If you've ever struggled with weird bugs or just want to get better at coding, you're in the right place. Through my blog, I share tips, solutions, and insights to help you code smarter and debug faster. Let’s make coding less frustrating and more fun! My LinkedIn Follow Me on X

0 Comments

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